【问题标题】:C# file writing - random character insertedC# 文件写入 - 插入随机字符
【发布时间】:2012-06-16 02:33:10
【问题描述】:

我正在使用 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

这是一个一贯的问题,我不确定哪里出了问题。

【问题讨论】:

  • 向我们展示// some processing 究竟是什么?
  • // some processing 部分有什么内容?会不会是你在那儿写东西?
  • 好吧,我删除了“一些处理”来生成这个输出。所以这并不重要

标签: c# file stream


【解决方案1】:

您为什么使用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");

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2016-04-23
    • 2013-05-15
    • 2022-07-21
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多