需要命名空间
using System.IO;
界面:
记得添加openFileDialog
注意名字,改成跟代码里的对应
写文件按钮代码:
private void button2_Click(object sender, EventArgs e)
{
int i = 0;
StreamWriter aFile = null;
aFile = File.CreateText("aFile .csv");
//aFile.WriteLine(i.ToString() + "," + (i + 1).ToString() + "," + (i + 2));
aFile.WriteLine("\"" + i.ToString() + "," + (i + 1).ToString() + "," + (i + 2)+"\"");
//aFile.WriteLine("\""+i.ToString() + "," + (i + 1).ToString() +"\""+ "," + (i + 2));
aFile.Close();
aFile.Dispose();
MessageBox.Show("end!");
}
注意逗号分隔符的用法,逗号分隔符把内容分成几个单元格.
如果要在同一个单元格中写入逗号,则要在该单元格内容前后加上双引号加上,3种情况产生的格式如下:
aFile.WriteLine(i.ToString() + "," + (i + 1).ToString() + "," + (i + 2));
aFile.WriteLine("\"" + i.ToString() + "," + (i + 1).ToString() + "," + (i + 2)+"\"");
aFile.WriteLine("\""+i.ToString() + "," + (i + 1).ToString() +"\""+ "," + (i + 2));
读文件按钮按钮:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string str = null;
FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs, System.Text.Encoding.UTF8);
while ((str = reader.ReadLine()) != null)
{
// split the string
//MessageBox.Show(str);
string[] strs = str.Split(',');
string show_str = "";
for(int i=0;i<strs.Length;i++)
{
if (i == strs.Length-1)
{
show_str += strs[i].ToString();
}
else
{
show_str += strs[i].ToString() + ",";
}
}
this.label1.Text = show_str;
}
reader.Close();
}
}
上面三种写入方式读出的字符串对应如下:
对应读出的字符串:
str=0,1,2
即strs[0]=0
strs[1]=1
strs[2]=2
对应的字符串:
str="0,1,2",
即strs[0]="0
strs[1]=1
strs[2]=2"
对应的字符串:
str="0,1",2,
即strs[0]="0
strs[1]=1"
strs[2]=2