简体   繁体   English

在StreamWriter中使用file.Close()

[英]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. 我在尝试使用该文件时遇到问题。在此方法中使用StreamWriter关闭,它似乎不喜欢它。 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);
        }
    }
}

The StreamWriter is closed aswell as flushed due to the "using" statement. 由于“使用”语句,StreamWriter也会关闭以及刷新。 So no need to call close. 因此,无需调用close。

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM