StreamWriter 不将任何文本写入文件
StreamWriter don't writing any text to file
我写了一些代码,应该写入文件一些文本:
private static FileStream CreateFile()
{
string _fileName = "znaki.txt";
if(File.Exists(_fileName))
{
File.Delete(_fileName);
}
FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write);
Console.Clear();
Console.Write("Ile znakok chcesz wygenerowac? >> ");
int lp;
lp = Convert.ToInt32(Console.ReadLine());
Random r = new Random();
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < lp; i++)
{
Console.Clear();
Console.WriteLine(i + "/" + lp);
sw.WriteLine("jogurcik");
}
return fs;
}
此代码创建文件但不写入任何内容。这段代码有什么问题?
在写入例程结束时关闭 StreamWriter(以及 FileStream):
sw.Close();
fs.Close();
MSDN:
You must call Close to ensure that all data is correctly written out
to the underlying stream... Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close.
P.S。
替代方法是使用有助于自动关闭和处理 IO 对象的 using
语句:
using (FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write))
{
...
using (StreamWriter sw = new StreamWriter(fs))
{
for (int i = 0; i < lp; i++)
{
...
sw.WriteLine("jogurcik");
}
}
}
在这种情况下,您可以省略关闭调用。
我写了一些代码,应该写入文件一些文本:
private static FileStream CreateFile()
{
string _fileName = "znaki.txt";
if(File.Exists(_fileName))
{
File.Delete(_fileName);
}
FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write);
Console.Clear();
Console.Write("Ile znakok chcesz wygenerowac? >> ");
int lp;
lp = Convert.ToInt32(Console.ReadLine());
Random r = new Random();
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < lp; i++)
{
Console.Clear();
Console.WriteLine(i + "/" + lp);
sw.WriteLine("jogurcik");
}
return fs;
}
此代码创建文件但不写入任何内容。这段代码有什么问题?
在写入例程结束时关闭 StreamWriter(以及 FileStream):
sw.Close();
fs.Close();
MSDN:
You must call Close to ensure that all data is correctly written out to the underlying stream... Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close.
P.S。
替代方法是使用有助于自动关闭和处理 IO 对象的 using
语句:
using (FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write))
{
...
using (StreamWriter sw = new StreamWriter(fs))
{
for (int i = 0; i < lp; i++)
{
...
sw.WriteLine("jogurcik");
}
}
}
在这种情况下,您可以省略关闭调用。