6

The following code writes the data and is working fine, but I want to add more than one client (maybe 10) in the .csv file. How can I achieve this. Thanks in advance.

private void createFileButton_Click(object sender, EventArgs e)
{
    string newFileName = "C:\\client_20100913.csv";

    string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;

    //Header of the .csv File
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
    File.AppendAllText(newFileName, clientDetails);

    MessageBox.Show("Client Added", "Added", MessageBoxButtons.OK); 
}
1
  • 2
    Why cant you loop and use AppendAllText in the loop? Each time change the value for clientdetails. Commented Sep 13, 2010 at 15:43

9 Answers 9

16

If you want to append the client information to an existing file, how about:

string newFileName = "C:\\client_20100913.csv";

string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;


if (!File.Exists(newFileName))
{
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

File.AppendAllText(newFileName, clientDetails);

This way the header line is only written the first time, when the file is created.

Although it would probably be even nicer to provide a list-detail view that lets you view all clients, add and remove clients, select a client to edit details, and save the complete file with all clients.

Sign up to request clarification or add additional context in comments.

3 Comments

The user will enter client information from the textboxes. When one clinet is added it shd clear the textboxes and then user can enter another client information and then click add. After user clicks generate .csv that will generate file having two clints in there.
Once the file is created I want to keep adding text to it.
Is there any way where I can store inputs into array and then append the array to the file??
1

It looks to me like you want a new client to be added every time you click the button.

If that's the case, the reason why it doesn't work currently is that the file is being cleared by the line

File.WriteAllText(newFileName, clientHeader);

The simplest change would be to check if the file exists before writing over it:

if (!File.Exists(newFileName))
{
    //Header of the .csv File
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

Although you could use other strategies, such as creating the file on startup of the application and keeping it open (using something like a StreamWriter). You would then close the writer when your application exited. This would pretty much guarantee that the file couldn't be messed with while your application is open.

You might want to do this because there is a race condition in that code - after you check the file exists, and before you write to the file, a user could delete it. Keeping the file open helps to avoid this, but you may or may not want to do it.

3 Comments

Is there any way where I can store inputs into array and then append the array to the file?? that way i can get 10 clients info. from the user and will then add it to the file
@Ani - yep, off the top of my head, if you store the clients in a String[] you can use File.WriteAllLines
yes, even i was thinking the same, but I used the above approach and achieved it. Is there anyway to also put date to the name of the file.
0

The underlying problem here seems to be where you're getting the data from to append to your CSV file. Your example code looks like it gets the various pieces of data from text boxes on the page, so if you want multiple clients, are they all going to have their data on the screen in text boxes? My instinct is probably not.

It sounds to me like you should be handling this client data using a class of some sort (perhaps persisted in a database) and then implement a method in the class called something like void AppendToCSV(string filename), which appends that client data to the CSV file. Then you can loop over your client objects, appending each one in turn.

How you produce/store your client objects, in relation to the text boxes you have on the screen, depends on what your app is trying to achieve.

2 Comments

Yes I am getting the input from textboxes. The user want to add multiple clients to .csv file.
So I guess your app will follow some kind of CRUD pattern, so that the user can add clients one by one and they are added to some kind of container or database, and finally serialised out to CSV.
0

I know this has been answered but there is what i did to create a "log" of subscribers. This uses reflection to get the properties and values of the object. Hope this helps someone in the future.

 internal static bool UpdateSubscriberList(MailingListEmail subscriber)
    {
        PropertyInfo[] propertyinfo;
        propertyinfo = typeof(MailingListEmail).GetProperties();
        var values = string.Empty;
        try
        {
            string fileName = @"C:\Development\test.csv";
            if (!File.Exists(fileName))
            {

                var header = string.Empty;
                foreach (var prop in propertyinfo)
                {
                    if (string.IsNullOrEmpty(header))
                        header += prop.Name;
                    else
                        header = string.Format("{0},{1}", header, prop.Name);


                }
                header = string.Format("{0},{1}", header, "CreatedDate");
                header += Environment.NewLine;
                File.WriteAllText(fileName, header);

            }


                foreach (var prop in propertyinfo)
                {
                    var value = prop.GetValue(subscriber, null);

                    if (string.IsNullOrEmpty(values))
                        values += value;
                    else
                        values = string.Format("{0},{1}", values, value);

                }
                values = string.Format("{0},{1}", values, DateTime.Now.ToShortDateString());

                values += Environment.NewLine;
                File.AppendAllText(fileName, values);



        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            return false;
        }


        return true;
    }

Comments

0

here is what i have done, and it works for me perfectly : first you need to creat DataTable from your listview, or just put data from textboxes:

 `public Boolean PreparCVS(string DateOne, string DataTwo)
    {
        try
        {
        // Create the `DataTable` structure according to your data source

            DataTable table = new DataTable();
            table.Columns.Add("HeaderOne", typeof(string));
            table.Columns.Add("HeaderTwo", typeof(String));

            // Iterate through data source object and fill the table
            table.Rows.Add(HeaderOne, HeaderTwo);
            //Creat CSV File
            CreateCSVFile(table, sCsvFilePath);
            return true;
        }
        catch (Exception ex)
        {
            throw new System.Exception(ex.Message);
        }
    }`

once dataTable is created you can generate CSV file by this method : in the streamwriter constructor you must specify in the second parameter True, by this, you can append data to you existing .csv file :

public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        StreamWriter sw = new StreamWriter(strFilePath, true);

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

Comments

0
// At first read all the data from your first CSV

StreamReader oStreamReader = new StreamReader(@"d:\test\SourceFile.csv");
string recordsFromFirstFile = oStreamReader.ReadToEnd();
oStreamReader.Close();

// Now read the new records from your another csv file
oStreamReader = new StreamReader(@"d:\test\DestinationFile.csv");
string recordsFromSecondFile = oStreamReader.ReadToEnd();
oStreamReader.Close();
oStreamReader.Dispose();

// Here Records from second file will also contain column headers so we need to truncate them using Substring() method

recordsFromSecondFile = recordsFromSecondFile.Substring(recordsFromSecondFile.IndexOf('\n') + 1);

// Now merge the records either in SourceFile.csv or in Targetfile.csv or as per your required file

StreamWriter oStreamWriter= new StreamWriter(@"d:\testdata\TargetFile.csv");
oStreamWriter.Write(recordsFromFirstFile + recordsFromSecondFile);
oStreamWriter.Close();
oStreamWriter.Dispose();

Happy Coding.....

Comments

0

using CsvHelper;

public void WriteDataToCsv(MsgEnvironmentData[] data, string csvPath) {

   if (!File.Exists(csvPath))
   {
     using (var writer = new StreamWriter(csvPath))
     using (var csvWriter = new CsvWriter(writer,firstConfiguration))
      {

          csvWriter.WriteHeader<MsgEnvironmentData>();
          csvWriter.NextRecord();
          csvWriter.WriteRecords(data);
      }
   }
   else
   {
       using (var stream = new FileStream(csvPath, FileMode.Append))
       using (var writer = new StreamWriter(stream))
       using (var csvWriter = new CsvWriter(writer, secondConfiguration))
        {
            csvWriter.WriteRecords(data);
        }
    }

}

Comments

0

Jeramy's answer writing the contents on last cell and from their horizontally in a row in csv file. I mixed and matched his solution with answer given here. I know this questions been asked long before but for the ones who doing research I'm posting the answer here.

string newFileName = @"C:\.NET\test.csv"; //filepath
var csv = new StringBuilder();
string clientDetails = "content1,content2,content3" + Environment.NewLine;
csv.Append(clientDetails);
File.AppendAllText(newFileName, csv.ToString());

Comments

0

I use this simple piece of code to append data to an existing CSV file:

        string[] data = { "John", "Doe", "25" };
        string csvFilePath = "example.csv";

        // Open the file for writing
        using (StreamWriter writer = File.AppendText(csvFilePath))
        {
            // Write the data row
            writer.WriteLine(string.Join(",", data));
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.