C #: Reading CSV file, saving as CSV file

Source: Internet
Author: User
Tags file info flush
Read CSV file:

In many systems, you need to read the CSV file, I also encountered in a previous project to read the data in the CSV file to the DataTable for processing, the following code

It's a method I wrote about importing data from a CSV file into a DataTable, and now it's posted for you to share:

Getcsvfile ' S FileName and data gets a CSV file and imports the data into the DataTable

MYCSVDT is used to mount the data in a CSV file Datatable,filepath is the path to the CSV file

private bool Opencsvfile (ref DataTable mycsvdt,string filepath)
{
string strpath = filepath; The path of the CSV file
Try
{
int intcolcount = 0;
bool Blnflag = true;

DataColumn MYDC;
DataRow myDR;

String strline;
string [] aryline;
StreamReader MYSR = new StreamReader (Strpath,system.text.encoding.default);

while (strline = MYSR. ReadLine ())!= null)
{
Aryline = strline. Split (New char[]{', '});

Add a column name to a DataTable
if (Blnflag)
{
Blnflag = false;
Intcolcount = Aryline. Length;
int col=0;
for (int i = 0; i < Aryline. Length; i++)
{
col=i+1;
MYDC = new DataColumn (col. ToString ());
Mycsvdt. Columns.Add (MYDC);
}
}

Fill the data and add it to the DataTable
myDR = Mycsvdt. NewRow ();
for (int i = 0; i < Intcolcount; i++)
{
Mydr[i] = Aryline[i];
}
Mycsvdt. Rows.Add (MYDR);
}
return true;

}
catch (Exception e)
{


Throw (Stack.geterrorstack (strpath+) Error reading data in CSV file. "+ E.message, Opencsvfile ("));
return false;
}
}
Save CSV file:

protected void Button1_Click (object sender, EventArgs e)
{
DataTable dt = new DataTable ();
Dt. Columns.Add ("Test1");
Dt. Columns.Add ("Test2");
Dt. Columns.Add ("Test3");
Dt. Columns.Add ("test4");
Dt. Columns.Add ("Test5");
for (int i = 0; i < 6; i++)
{
Dt. Rows.Add ();
Dt. Rows[i][0] = "CN" +i.tostring ();
Dt. ROWS[I][1] = "EN" +i.tostring ();
Dt. ROWS[I][2] = "JN" +i.tostring ();
Dt. ROWS[I][3] = "HK" +i.tostring ();
Dt. ROWS[I][4] = "TW" +i.tostring ();
}

Exportdatagridtocsv (DT);

}

<summary>
Export the data from DataTable to CSV file
</summary>
<param name= "Grid" ></param>
public void Exportdatagridtocsv (DataTable dt)
{
String strfile = "";
String path = "";

File Info Initialization
strfile = "Test";
strfile = strfile + DateTime.Now.ToString ("Yyyymmddhhmmss");
strfile = strfile + ". csv";
Path = Server.MapPath (strfile);



System.IO.FileStream fs = new FileStream (path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = New StreamWriter (FS, New System.Text.UnicodeEncoding ());
Tabel header
for (int i = 0; i < dt. Columns.count; i++)
{
Sw. Write (dt. Columns[i]. ColumnName);
Sw. Write ("T");
}
Sw. WriteLine ("");
Table body
for (int i = 0; i < dt. Rows.Count; i++)
{
for (int j = 0; j < dt.) Columns.count; J + +)
{
Sw. Write (Delquota (dt. ROWS[I][J]. ToString ()));
Sw. Write ("T");
}
Sw. WriteLine ("");
}
Sw. Flush ();
Sw. Close ();

DownLoadFile (path);
}

private bool DownLoadFile (string _filename)
{
Try
{
System.IO.FileStream fs = System.IO.File.OpenRead (_filename);
byte[] Filedata = new Byte[fs. Length];
Fs. Read (filedata, 0, (int) fs. Length);
Response.Clear ();
Response.AddHeader ("Content-type", "Application/notepad");
String FileName = System.Web.HttpUtility.UrlEncode (System.Text.Encoding.UTF8.GetBytes (_filename));
Response.AddHeader ("Content-disposition", "inline;filename=" + System.Convert.ToChar (+) + filename + System.Convert.ToChar (34));
Response.AddHeader ("Content-length", FS. Length.tostring ());
Response.BinaryWrite (Filedata);
Fs. Close ();
System.IO.File.Delete (_filename);
Response.Flush ();
Response.End ();
return true;
}
catch (Exception ex)
{
Ex. Message.tostring ();
return false;
}
}



<summary>
Delete Special Symbol
</summary>
<param name= "str" ></param>
<returns></returns>
public string Delquota (String str)
{
string result = str;
String[] Strquota ={"~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "'", ";", "", ",", ".", "/", ",", " < "," > ","? "};
for (int i = 0; i < strquota.length; i++)
{
if (result. IndexOf (Strquota[i]) >-1)
result = result. Replace (Strquota[i], "");
}
return result;
}

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.