我正在尝试将文件读入字符串并将该字符串重写为新文件,但是如果当前字符是我要重写的特殊字符之一,则会进行一次小检查。 我调试了它,代码似乎工作正常,但输出文件是空的..我想我错过了什么......但是什么?
StreamWriter file = new StreamWriter(newname, true);
char current;
int j;
string CyrAlph = "йцукен";
string LatAlph = "ysuken";
string text = File.ReadAllText(filename);
for (int i = 0; i < text.Length; i++)
{
if (CyrAlph.IndexOf(text[i]) != -1)
{
j = CyrAlph.IndexOf(text[i]);
current = LatAlph[j];
}
else current = text[i];
file.Write(current);
}
答案 0 :(得分:1)
如果您在file.AutoFlush = true
实例化后设置StreamWriter
或在编写所有内容时调用file.Close
,或者您可以在using
语句中实例化StreamWriter,会发生什么情况。我的猜测是它是空的,因为缓冲区需要刷新
答案 1 :(得分:0)
StreamWriter
实施IDisposable
。使用后你“拥有”Dispose
。为此,请使用using
语句。这将自动刷新并关闭using
正文末尾的流。
using(StreamWriter file = new StreamWriter(newname,true))
{
char current;
int j;
string CyrAlph="йцукен";
string LatAlph = "ysuken";
string text = File.ReadAllText(filename);
for (int i = 0; i < text.Length; i++)
{
if (CyrAlph.IndexOf(text[i]) != -1)
{
j=CyrAlph.IndexOf(text[i]);
current = LatAlph[j];
}
else current=text[i];
file.Write(current);
}
}
答案 2 :(得分:0)
你错过了一个流冲洗。标准模式是在StreamWriter的分配周围添加using
语句。它还负责关闭文件并释放操作系统的文件句柄:
using (StreamWriter file = new StreamWriter(path, true))
{
// Work with your file here
} // After this block, you have "disposed" of the file object.
// That takes care of flushing the stream and releasing the file handle
即使在块中发生异常的情况下,using语句还有明显关闭流的额外好处,即正确处理流。