命名空间:using System.IO;
读取txt文件内容:
string filePath = "111.txt";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader strReader = new StreamReader(fs,Encoding.Default);
string sLine = "";
dtDetails = DMaterialInventory.CreateTmpTable();
while (!strReader.EndOfStream)
{
sLine = strReader.ReadLine();
string[] cList = sLine.Split(',');
DataRow dtRow = dtDetails.NewRow();
dtRow["编码"] = cList[0].ToString();
Msg.InfoBox(cList[1].ToString());
dtRow["姓名"] = cList[1].ToString();
dtRow["数量"] = cList[2].ToString();
dtDetails.Rows.Add(dtRow);
}
strReader.Close();
fs.Close();
写入内容到txt文件:
public bool SaveTXT(DataTable dt)
{
try
{
string filePath = "111.txt";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamWriter strWriter = new StreamWriter(fs, Encoding.Default);
foreach (DataRow row in dt.Rows)
{
string strData = "";
foreach (DataColumn col in dt.Columns)
{
strData += row[col.ColumnName].ToString();
strData += ",";
}
strData = strData.Substring(0, strData.Length - 1);
Msg.InfoBox(strData);
strWriter.WriteLine(strData);
}
strWriter.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
throw ex.Message;
}
}
写入内容到txt文件(可弹窗选择保存路径):
//写入内容到txt文件:
string savePath = "";
SaveFileDialog savef = new SaveFileDialog();
savef.Filter = "文本文件|*.txt";
savef.FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
if (savef.ShowDialog() == DialogResult.OK)
{
savePath = savef.FileName;
}
if (savePath != "")
{
FileStream fs = new FileStream(savePath, FileMode.Create);
StreamWriter strWriter = new StreamWriter(fs, Encoding.Default);
DataTable dt = this.dgDetails.DataSource as DataTable;
foreach (DataRow row in dt.Rows)
{
string strData = "";
strData += row["条码"].ToString();
strData += "\r";
strWriter.WriteLine(strData);
}
strWriter.Close();
fs.Close();
}
浙公网安备 33010602011771号