Reputation: 303
I am working with Visual Studio 2008 to write a C# utility to merge database script for release.
Here is what the code looks like
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");
This code runs fine and create a script.sql file as required; but with random characters
=
/*--------- script1.sql -------------*/
A
/*--------- script2.sql -------------*/
I
/*--------- script3.sql -------------*/
H
This is a consistent issue and I am not sure what is wrong.
Upvotes: 2
Views: 992
Reputation: 1039438
Why are you using a BinaryWriter? As its name indicates this is for writing binary files, not text files. Use a StreamWriter instead. Also make sure you have wrapped IDisposable
resources in using
statements:
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");
Or use LINQ to simplify your code:
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");
Upvotes: 4