将 file.Close() 与 StreamWriter 一起使用
我在尝试使用 file.Close 与 StreamWriter 在此方法中遇到问题,它似乎不喜欢它。有人可以演示如何做到这一点吗? (原因是,另一种方法访问正在使用的文件,因此无法访问,因为该文件仍在由另一种方法使用。)
到目前为止的代码:
private static void TrimColon()
{
using (StreamWriter sw = File.AppendText(@"process_trimmed.lst"))
{
StreamReader sr = new StreamReader(@"process_trim.lst");
string myString = "";
while (!sr.EndOfStream)
{
myString = sr.ReadLine();
int index = myString.LastIndexOf(":");
if (index > 0)
myString = myString.Substring(0, index);
sw.WriteLine(myString);
}
}
}
I am having problems trying to use the file.Close with StreamWriter in this method, it doesn't seem to like it. Could someone demonstrate how this could be done. (The reason so, is that another method accesses a file being used and hence can't, because the file is still in use by the other method.)
Code so far:
private static void TrimColon()
{
using (StreamWriter sw = File.AppendText(@"process_trimmed.lst"))
{
StreamReader sr = new StreamReader(@"process_trim.lst");
string myString = "";
while (!sr.EndOfStream)
{
myString = sr.ReadLine();
int index = myString.LastIndexOf(":");
if (index > 0)
myString = myString.Substring(0, index);
sw.WriteLine(myString);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于“using”语句,StreamWriter 被关闭并刷新。所以不需要调用 close。
The StreamWriter is closed aswell as flushed due to the "using" statement. So no need to call close.