C # file for. csv format--read and write of comma separated values and how to upload FTP server operation method Summary

Source: Internet
Author: User


Objective


The company recently developed the need to save data to a. CSV file (comma separated values) and then upload to the FTP server, for our system also has a customer system call, before completely did not contact this, so first to look at the explanation of Baidu: comma-separated values (comma-separated values,csv , sometimes referred to as character-delimited values, because delimited characters can also be not commas, and their files store tabular data (numbers and text) in plain text. Plain text means that the file is a sequence of characters and does not contain data that must be interpreted like a binary number. A CSV file consists of any number of records separated by a newline character, each record consists of a field, and the delimiter between the fields is another character or string, most commonly a comma or tab. Typically, all records have exactly the same sequence of fields.



The common criteria for the CSV file format do not exist, but there is a basic description in RFC 4180. The character encoding used is also not specified, but 7-BITASCII is the most basic generic encoding.



In short, the comma is separated by a double quotation mark is the value of the data format does not have a very uniform standard but in order to avoid the error we developed the uniform format is this



"Name", "pwd", "date"



"Zhang San", "123", "2015-09-30"



And then the default format for code processing is that it's actually the form of plain text.


Why use a CSV file


This involves data interoperability issues, some programs support the tabular data other programs are not supported, and CSV format is supported by most applications, so in exchange for saving data is a good choice.






And the need to do in the project development process is not very simple



For example, a CSV file to read data conversion (such as into a DataTable), CSV file renaming, CSV file write, file upload to the FTP server and so on



Here will develop a simple arrangement of methods, in case of a rainy day, a short time, there are a lot of shortcomings of the point.


Note the point


① when the file is finished, you must remember to close the release stream otherwise the file will be occupied



②csv does not have strict standards, the development of a lot of people must specify a good format, unified development


First, read the CSV file data into the DataTable


First of all, in order to facilitate management, in the Web site often need to read the data in the CSV file and display on the site for easy query. So the more convenient way is to see the CSV file data into a DataTable form, the code is as follows.


/// <summary>
/// Read data from CSV file into DataTable
/// </ summary>
/// <param name = "fileName"> CSV file path </ param>
/// <returns> return the DataTable that reads the CSV data </ returns>
public static DataTable OpenCSV (string filePath)
{
    DataTable dt = new DataTable ();
    FileStream fs = new FileStream (filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

    StreamReader sr = new StreamReader (fs, Encoding.UTF8);
    // StreamReader sr = new StreamReader (fs, encoding);
    // string fileContent = sr.ReadToEnd ();
    // Record a row of records read each time
    string strLine = "";
    // Record the content of each field in each line of records
    string [] aryLine = null;
    string [] tableHead = null;
    // Mark the number of columns
    int columnCount = 0;
    // Indicate whether it is the first line read
    bool IsFirst = true;
    // Read the data in CSV line by line
    while ((strLine = sr.ReadLine ())! = null)
    {

        if (IsFirst == true)
        {
            tableHead = strLine.Split (‘,’);
            IsFirst = false;
            columnCount = tableHead.Length;
            // Create column
            for (int i = 0; i <columnCount; i ++)
            {
                tableHead [i] = tableHead [i] .Replace ("\" "," ");
                DataColumn dc = new DataColumn (tableHead [i]);
                dt.Columns.Add (dc);
            }
        }
        else
        {
            aryLine = strLine.Split (‘,’);
            DataRow dr = dt.NewRow ();
            for (int j = 0; j <columnCount; j ++)
            {
                dr [j] = aryLine [j] .Replace ("\" "," ");
            }
            dt.Rows.Add (dr);
        }
    }
    if (aryLine! = null && aryLine.Length> 0)
    {
        dt.DefaultView.Sort = tableHead [2] + "" + "DESC";
    }

    sr.Close ();
    fs.Close ();
    return dt;
} 




Ii. writing data from a DataTable to a CSV file


Of course, the data in one file is migrated to another file, or the data queried directly from the database is inserted into the CSV file, one way is to relay through a DataTable, so the DataTable needs to be converted to CSV code as follows:


/// <summary>
/// Write data from DataTable to CSV file
/// </ summary>
/// <param name = "dt"> Provide a DataTable that holds data </ param>
/// <param name = "fileName"> File path of CSV </ param>
public static bool SaveCSV (DataTable dt, string fullPath)
{
    try
    {
        FileInfo fi = new FileInfo (fullPath);
        if (! fi.Directory.Exists)
        {
            fi.Directory.Create ();
        }
        FileStream fs = new FileStream (fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        // StreamWriter sw = new StreamWriter (fs, System.Text.Encoding.Default);
        StreamWriter sw = new StreamWriter (fs, System.Text.Encoding.UTF8);
        string data = "";
        // Write column names
        for (int i = 0; i <dt.Columns.Count; i ++)
        {
            data + = "\" "+ dt.Columns [i] .ColumnName.ToString () +" \ "";
            if (i <dt.Columns.Count-1)
            {
                data + = ",";
            }
        }
        sw.WriteLine (data);
        // Write out each line of data
        for (int i = 0; i <dt.Rows.Count; i ++)
        {
            data = "";
            for (int j = 0; j <dt.Columns.Count; j ++)
            {
                string str = dt.Rows [i] [j] .ToString ();
                str = string.Format ("\" {0} \ "", str);
                data + = str;
                if (j <dt.Columns.Count-1)
                {
                    data + = ",";
                }
            }
            sw.WriteLine (data);
        }
        sw.Close ();
        fs.Close ();
        return true;
    }
    catch {
        return false;
    }
} 




Third, modify the file name


Modify the file name we need to save the historical data or real-time know that the file can be modified by changing the name of the file, including the date of the day and so convenient management


/// <summary>
/// modify the file name
/// </ summary>
/// <param name = "OldPath"> Old path full physical path </ param>
/// <param name = "NewPath"> New path </ param>
/// <returns> </ returns>
public static bool ChangeFileName (string OldPath, string NewPath) {
     bool re = false;
     // OldPath = HttpContext.Current.Server.MapPath (OldPath); virtual
     // NewPath = HttpContext.Current.Server.MapPath (NewPath);
     try {
         if (File.Exists (OldPath)) {
             File.Move (OldPath, NewPath);
             re = true;
         }
     }
     catch {
         re = false;
     }
     return re;
} 




Iv. data writes to SCV files


Submit data directly to a Web form to write files directly in a CSV file


1 /// <summary>
  2 /// write to file
  3 /// </ summary>
  4 /// <param name = "fullPath"> </ param>
  5 /// <param name = "Data"> </ param>
  6 /// <returns> </ returns>
  7 public static bool SaveCSV (string fullPath, string Data)
  8 {
  9 bool re = true;
10 try
11 {
12 FileStream FileStream = new FileStream (fullPath, FileMode.Append);
13 StreamWriter sw = new StreamWriter (FileStream, System.Text.Encoding.UTF8);
14 sw.WriteLine (Data);
15 // Empty the buffer
16 sw.Flush ();
17 // Close stream
18 sw.Close ();
19 FileStream.Close ();
20}
21 catch {
22 re = false;
twenty three     }
24 return re;
25} 





C # file for. csv format--read and write of comma separated values and how to upload FTP server operation method Summary


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.