Using file.Close() with StreamWriter
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);
}
}
}
private static void TrimColon(String inputFilePath, String outputFilePath)
{
//Error checking file paths
if (String.IsNullOrWhiteSpace(inputFilePath))
throw new ArgumentException("inputFilePath");
if (String.IsNullOrWhiteSpace(outputFilePath))
throw new ArgumentException("outputFilePath");
//Check to see if files exist? - Up to you, I would.
using (var streamReader = File.OpenText(inputFilePath))
using (var streamWriter = File.AppendText(outputFilePath))
{
var text = String.Empty;
while (!streamReader.EndOfStream)
{
text = streamReader.ReadLine();
var index = text.LastIndexOf(":");
if (index > 0)
text = text.Substring(0, index);
streamWriter.WriteLine(text);
}
}
}
The StreamWriter is closed aswell as flushed due to the "using" statement. So no need to call close.
精彩评论