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);
}
}

Sarthak VarshneyRank #46 · 32K reputationPosted May 24, 2024, 9:24 PM EDT
To achieve the desired functionality of removing the dynamic portion of the string in your CSV processing, you need to use a regular expression that matches the pattern you're trying to remove. This way, you can account for the incrementing part at the end of the string. Below is the modified version of your code with added regular expression to remove the required dynamic strings.
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; 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; // Define the regex pattern for the dynamic string string pattern = @".\\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_\d{4}\\"; Regex regex = new Regex(pattern); foreach (var line in lines) { // Remove the dynamic part of the string using regex var cleanedLine = regex.Replace(line, ""); // Process the cleaned line var newLine = cleanedLine.Replace("\"", "").Replace(".\\", "").Replace("\\", "").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); } }Key Changes and Additions:
@".\\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_\d{4}\\"to match and remove the dynamic part of the string. This pattern will match any sequence like.\\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001\\,.\\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0002\\, etc.regex.Replace(line, "")to remove the matched substring from each line before processing it further.|separator.This approach ensures that any dynamically incremented part of the string is removed effectively regardless of its value, meeting the requirement specified.
Prasad RaveendranRank #320 · 7.8K reputationPosted May 26, 2024, 12:10 AM EDT
Here are a few suggested improvements:
StringBuilderto accumulate lines before writing to the file: This reduces the overhead of opening and closing the file repeatedly within the loop.usingblocks: Open theStreamWriteronce and use it throughout the processing.Application.DoEvents(): It can lead to reentrancy issues and isn't generally recommended. Consider using a background worker for long-running operations if necessary.Here is the revised code:
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Text; private void button2_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(FromFile)) { lblStatus.Text = "Missing CSV Information"; MessageBox.Show("Please select a CSV file first."); return; } if (string.IsNullOrEmpty(ToFile)) { lblStatus.Text = "Missing Save Information"; MessageBox.Show("Please enter save information."); return; } else if (File.Exists(ToFile)) { File.Delete(ToFile); } btnProcess.Enabled = false; lblStatus.Text = "Processing..."; var lines = File.ReadAllLines(FromFile).Skip(1); string docId = ""; string[] oldLine = null; string pattern = @"\.\\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_\d{4}\\"; var sb = new StringBuilder(); foreach (var line in lines) { var newLine = Regex.Replace(line, pattern, "").Replace("\"", "").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]; } sb.AppendLine(string.Join("|", newLine)); } File.WriteAllText(ToFile, sb.ToString()); btnProcess.Enabled = true; lblStatus.Text = "Completed"; } catch (FileNotFoundException ex) { MessageBox.Show($"File not found: {ex.Message}"); } catch (IOException ex) { MessageBox.Show($"IO error: {ex.Message}"); } catch (UnauthorizedAccessException ex) { MessageBox.Show($"Access denied: {ex.Message}"); } catch (Exception ex) { MessageBox.Show($"An unexpected error occurred: {ex.Message}"); } finally { btnProcess.Enabled = true; lblStatus.Text = "Ready"; } }StringBuilderfor Accumulating Lines:StringBuilderto collect all lines and write them to the file in one go. This is more efficient and reduces the file I/O operations.Optimized
usingBlock:StreamWriteronce at the end, outside the loop, and write all lines at once. This reduces the overhead associated with repeatedly opening and closing the file.Error Handling:
Removed
Application.DoEvents():Application.DoEvents(), which can cause reentrancy issues and is generally not recommended.Final
finallyBlock:btnProcess.EnabledandlblStatus.Textare reset even if an exception occurs, ensuring the UI state is consistent.Ivonne AspilcuetaRank #4,887 · 320 reputationPosted May 28, 2024, 11:21 AM EDT
Thank you so much to everyone. I was not expecting to receive so much useful help!
Thank you for teaching as well, I really appreciate it!
Tuhin PaulRank #7 · 71.9K reputationPosted May 30, 2024, 10:08 PM EDT
private void button2_Click(object sender, EventArgs e) { try { // Check for CSV file and save information if (String.IsNullOrEmpty(FromFile)) { lblStatus.Text = "Missing CSV Information"; MessageBox.Show("Please select CSV file first."); return; } if (String.IsNullOrEmpty(ToFile)) { lblStatus.Text = "Missing Save Information"; MessageBox.Show("Please enter save information."); return; } // Rename file if it already exists if (File.Exists(ToFile)) { File.Move(ToFile, ToFile + ".bak"); } btnProcess.Enabled = false; lblStatus.Text = "Processing..."; // Compile regex pattern outside the loop for optimization string pattern = @".\\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_\d{4}\\"; Regex regex = new Regex(pattern); // Use using statement for StreamWriter using (StreamWriter sr = new StreamWriter(ToFile, true)) { var lines = File.ReadAllLines(FromFile).Skip(1); string docId = ""; string[] oldLine = null; foreach (var line in lines) { // Remove the dynamic part of the string using regex var cleanedLine = regex.Replace(line, ""); // Process the cleaned line var newLine = cleanedLine.Replace("\"", "").Replace(".\\", "").Replace("\\", "").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]; } // Write processed line to file sr.WriteLine(string.Join("|", newLine)); } } lblStatus.Text = "Completed"; } catch (FileNotFoundException ex) { MessageBox.Show("Error! File not found. " + ex.Message); } catch (IOException ex) { MessageBox.Show("Error! IO Exception occurred. " + ex.Message); } catch (Exception ex) { MessageBox.Show("Error! " + ex.Message); } finally { btnProcess.Enabled = true; } }some modification made which can increase performance, and readability of the code, making it more maintainable and user-friendly.
Tuhin PaulRank #7 · 71.9K reputationPosted May 30, 2024, 10:10 PM EDT
The code also uses
Application.DoEvents()calls which can lead to unexpected behavior and may not be necessary in this context. Instead, you can use background tasks or threading to keep the UI responsive without resorting toApplication.DoEvents().