Ivonne Aspilcueta

Ivonne Aspilcueta

  • 1.2k
  • 419
  • 687

Replace a string value in a CSV File with C#

May 24 2024 9:09 PM

Hello,

So far, with my code I am uploading a CSV file to format it as: I have skip the headers and also instead of comma separator , added a pipeline separator | and delete the following value: ".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\" in all lines/rows when creates the new CSV File. Thank you.

The problem that I was not able to resolve is when uploading a new CSV File, the value I need to delete: ".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\" . The last number: _0001\" increments by one on every  CSV file I upload to formatted.

I need help on how to delete the whole string value including the increment of last value: 

".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\" . The last number: _0001\"

".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\" . The last number: _0002\"

".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\" . The last number: _0003\"

".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\" . The last number: _0004\"

This is my code:

private void button2_Click(object sender, EventArgs e)
{
	try
	{
		if (String.IsNullOrEmpty(FromFile))
		{ 
			lblStatus.Text = "Missing CSV Information";
			Application.DoEvents();
			MessageBox.Show("Please select CSV file first.");
			return;
		}

		if (String.IsNullOrEmpty(ToFile))
		{
			lblStatus.Text = "Missing Save Information";
			Application.DoEvents();
			MessageBox.Show("Please enter save information.");
			return;
		}
		else if (File.Exists(ToFile))
		{
			// delete old file
			File.Delete(ToFile);
		}

		btnProcess.Enabled = false;
		lblStatus.Text = "Processing...";
		Application.DoEvents();

		var lines = File.ReadAllLines(FromFile).Skip(1);
		string docId = "";
		string[] oldLine = null;

		foreach (var line in lines)
		{
			var newLine = line.Replace("\"", "").Replace(".\\", "").Replace("\\", "").Replace("MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001", "").Split(',');

			if (docId != newLine[0])
			{
				docId = newLine[0];
				oldLine = newLine;
			} 
			else
			{
				for (int i = COPY_FROM - 1; i < newLine.Length; i++)
					newLine[i] = oldLine[i];
			}

			using (StreamWriter sr = new StreamWriter(ToFile, true))
			{
				sr.WriteLine(string.Join("|", newLine));
			}
		}

		btnProcess.Enabled = true;
		lblStatus.Text = "Completed";
		Application.DoEvents();
	}
	catch (Exception ex)
	{
		MessageBox.Show("Error! Ex: " + ex.Message);
	}
}

 


Answers (5)