>我正在使用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 = "rnrn/*--------- " + fi.Name + " -------------*/" + "rnrn";
writer.Write(strLine);
//some processing
}
foutput.Close();
MessageBox.Show("Done");
此代码运行良好,并根据需要创建一个脚本.sql文件;但使用随机字符
=
/*--------- script1.sql -------------*/
A
/*--------- script2.sql -------------*/
I
/*--------- script3.sql -------------*/
H
这是一个始终如一的问题,我不确定出了什么问题。
你为什么要使用 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 = "rnrn/*--------- " + fi.Name + " -------------*/" + "rnrn";
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(
"rnrn/*--------- {0} -------------*/rnrn{1}",
fi.Name,
File.ReadAllText(fi.FullName)
)
),
Encoding.UTF8
);
MessageBox.Show("Done");