1、读文件夹中的每个文件
string strSeaPath = @"C:\Users\Administrator\Desktop\国内浮标站数据\国内浮标站数据\海洋要素";
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strSeaPath);
foreach (System.IO.DirectoryInfo dirData in dir.GetDirectories())
{
System.IO.FileInfo file = dirData.GetFiles();
string strOneLine;
System.IO.StreamReader sr = new System.IO.StreamReader(file.FullName);
while (!sr.EndOfStream)
{
if ((strOneLine = sr.ReadLine()) != null)
{
strOneLine = strOneLine.Trim();
WriteToTxt(strOneLine);
}
}
sr.Close();
sr.Dispose();
}
2、将一行中连续多个空格替换成一个
//将一行中多个连续的空格变成一个空格
strOneLine = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(strOneLine, " ");
3、将内容写入TXT文件
#region WriteTxt():写入数据到TXT
private void WriteTxt(string strFilePath, string strText)
{
FileStream fs = new FileStream(strFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(strText);
sw.Flush();
sw.Close();
}
#endregion WriteTxt():写入数据到TXT
4、判断文件目录是否存在
string filePath = System.Windows.Forms.Application.StartupPath + "\\image\\" + FormSSKX.ZTH;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
if (yearFile.Directory.Exists)//文件夹是否存在
{
}
5、判断文件是否存在
if (File.Exists(strfilepath))
{
}
6、清空TXT文件内容
#region 清空TXT文件内容
private void ClearTxt(String txtPath)
{
FileStream stream = File.Open(txtPath, FileMode.Truncate, FileAccess.ReadWrite);
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);
FileStream stream = new FileStream(txtPath, FileMode.Truncate, FileAccess.ReadWrite);
stream.Close();
stream.Dispose();
}
#endregion 清空TXT文件内容