Click here to Skip to main content
15,611,107 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have many csv files arriving daily with ssn's in them and I need to replace the text with encrypted ssn.

I found some good examples on here and I have the csv file being read in line by line, and I can get the column I want (in this case column 12) and pass it to encrypt, and I can check the return value and it is encrypted, but where I am struggling is to then take that encrypted ssn and replace the original value in the csv file at each line.

I am getting hung up on either the replace method:

or the writer.WriteLine(stringJoin method:
writer.WriteLine(string.Join(delimiter, columns));

When I run the program the temp file is created, and the orginal is deleted and the new temp file replaces it. Problem is, it looks the same as original, no encrypted ssn.

While executing, I can see the tmp file in my temp folder, and if I break the code and look in the file, the ssn is not encrypted.

Does anyone know what I am doing wrong?

Here is that block of code:

private void btnEncrypt_Click(object sender, EventArgs e)
//Test file with 36 comma delimited columns, no quoted identifiers
var sourcePath = @"C:\TEST.TRD";
var delimiter = ",";
var tempPath = Path.GetTempFileName();
var lineNumber = 0;

var splitExpression = new Regex(@"(" + delimiter + @")(?=(?:[^""]|""[^""]*"")*$)");

using (var writer = new StreamWriter(tempPath))
using (var reader = new StreamReader(sourcePath))
string line = null;
string org = null;
string enc = null;
string password = "abcd1234";
// Get the bytes of the password string
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(password);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

while ((line = reader.ReadLine()) != null)

var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();

// Want to take ssn from 11th column in csv file (0 based), encrypt it, and replace it.

if (columns[12].Length > 0) org = columns[12];
enc = AES.Encrypt(org, passwordBytes);

columns[12].Replace(org, enc);
writer.WriteLine(string.Join(delimiter, columns));


File.Move(tempPath, sourcePath);

1 solution

To split a line you need:

string[] data = csv.Split(new char[]{','});

or make char array e.g: delimiter=","

string[] data = csv.Split(delimiter.ToCharArray());

Also 11th column is 10, 12th column is 11.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900