select csv file and add a new column with yes or no and move the new csv to destination in csharp

To select a CSV file in C#, we can use OpenFileDialog class from WinForms namespace. Here is how we can use OpenFileDialog to select a CSV file:

main.cs
using System.Windows.Forms;

OpenFileDialog openFileDialog = new OpenFileDialog();

// set filters to show only CSV files
openFileDialog.Filter = "CSV Files (*.csv)|*.csv";

if(openFileDialog.ShowDialog() == DialogResult.OK)
{
    // Selected CSV file path
    string filePath = openFileDialog.FileName;

    // add Yes/No column and save the CSV to destination
}
364 chars
15 lines

As we have got the file path, now we can add a new Yes/No column to the CSV and move the file to the destination. Here is the code to add a new column and move the CSV file to a destination folder:

main.cs
// Adding Yes/No column to CSV file
string[] fileLines = File.ReadAllLines(filePath);
List<string> updatedLines = new List<string>();

foreach (var line in fileLines)
{
    updatedLines.Add(line + ",Yes");
}

// Save the new file with Yes/No column
string newFilePath = Path.Combine(targetFolderPath, Path.GetFileNameWithoutExtension(filePath) + "_updated.csv");
File.WriteAllLines(newFilePath, updatedLines.ToArray());

// Move the CSV file to destination folder
if (File.Exists(newFilePath))
{
    File.Move(filePath, Path.Combine(targetFolderPath, Path.GetFileName(filePath)));
}
583 chars
19 lines

Here, targetFolderPath is the path of the destination folder where we want to move the updated CSV file.

This code reads all the lines from selected CSV file and adds a new Yes column to each line. After that, it saves the updated lines to a new CSV file named "_updated.csv". Finally, it moves the original CSV file to the destination folder and renames it with the original filename.

gistlibby LogSnag