C#文件写入 - 插入随机字符

时间:2012-06-13 07:01:59

标签: c# file stream

我正在使用Visual Studio 2008编写一个C#实用程序来合并数据库脚本以供发布。

这是代码的样子

strPath = txtInputFolder.Text;

DirectoryInfo di = new DirectoryInfo(strPath);
FileInfo[] lstFile = di.GetFiles("*.sql");

string strScriptPath = System.IO.Path.Combine(strPath, lblOutput.Text);
FileStream foutput = System.IO.File.Create(strScriptPath);
BinaryWriter writer = new BinaryWriter(foutput, Encoding.UTF8);

string strLine;
foreach (FileInfo fi in lstFile)
{
   strLine = string.Empty;

   strLine = "\r\n\r\n/*--------- " + fi.Name + " -------------*/" + "\r\n\r\n";
   writer.Write(strLine);

   //some processing
}

foutput.Close();
MessageBox.Show("Done");

此代码运行正常,并根据需要创建script.sql文件;但随机字符

      =

      /*--------- script1.sql -------------*/

      A

      /*--------- script2.sql -------------*/

      I

      /*--------- script3.sql -------------*/

      H

这是一个一致的问题,我不确定是什么问题。

1 个答案:

答案 0 :(得分:3)

为什么使用BinaryWriter?正如其名称所示,这是用于编写二进制文件,而不是文本文件。请改用StreamWriter。另外,请确保在IDisposable语句中包含using个资源:

strPath = txtInputFolder.Text;
DirectoryInfo di = new DirectoryInfo(strPath);
FileInfo[] lstFile = di.GetFiles("*.sql");

string strScriptPath = System.IO.Path.Combine(strPath, lblOutput.Text);
using (FileStream foutput = System.IO.File.Create(strScriptPath))
using (StreamWriter writer = new StreamWriter(foutput, Encoding.UTF8))
{

    string strLine;
    foreach (FileInfo fi in lstFile)
    {
        strLine = string.Empty;

        strLine = "\r\n\r\n/*--------- " + fi.Name + " -------------*/" + "\r\n\r\n";
        writer.Write(strLine);
        //some processing
    }
}
MessageBox.Show("Done");

或者使用LINQ来简化代码:

string strPath = txtInputFolder.Text;
DirectoryInfo di = new DirectoryInfo(strPath);
FileInfo[] lstFile = di.GetFiles("*.sql");

string strScriptPath = Path.Combine(strPath, lblOutput.Text);

File.WriteAllLines(
    strScriptPath, 
    lstFile.Select(
        fi => string.Format(
            "\r\n\r\n/*--------- {0} -------------*/\r\n\r\n{1}", 
            fi.Name, 
            File.ReadAllText(fi.FullName)
        )
    ),
    Encoding.UTF8
);

MessageBox.Show("Done");