开发者

List of strings wont get written completely to text file

I Im trying to read from one text file and write to another one. The file Im reading from has 2023 lines, and the file that 开发者_如何转开发I am writing to comes out with only 2008 lines. I cant figure out what is happening to the other line... Im losing them somewhere. What am I doing wrong?

thanks!

heres my code in C#.

     static void Main(string[] args)
    {
        StreamWriter writer = new StreamWriter("C:/Users/Rafael/desktop/newfile.txt");
        StreamReader reader = new StreamReader("C:/Users/Rafael/desktop/new1.txt");//, System.Text.Encoding.GetEncoding("ISO-8859-1"));
        string line;
        while ((line = reader.ReadLine()) != null)
        {

            writer.WriteLine(line);
        }

    }


At no point here are you closing the streamwriter - so it might not be written to the file. You can test this by putting a Close() call after the loop, or if you have not finished with the file, you can use Flush().

Given a choice, I would however rewrite the code to use Using{} blocks which would close the streams automatically by calling Dispose() when they go out of scope.


Most likely is that the output isn't being flushed since you aren't calling Dispose() on the writer, so the buffered output is being thrown away.

When you're using classes that implement IDisposable in this way, you should always wrap them in using blocks:

static void Main(string[] args)
{
    using (StreamWriter writer = new StreamWriter("C:/Users/Rafael/desktop/newfile.txt"))
    using (StreamReader reader = new StreamReader("C:/Users/Rafael/desktop/new1.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {

            writer.WriteLine(line);
        }
    }
}


This is where implementation details matter a lot. Basically when you write to a StreamWriter, the text that you write isn't necessarily committed to the file on the disk. Instead, it could sit in a buffer somewhere and that buffer has to be flushed to be committed to the disk. Periodically, this buffer will be flushed by the StreamWriter itself. But if you let your process terminate without making a final flush, the buffer could still hold uncommitted writes.

So, call writer.Flush, writer.Close, writer.Dispose, or best of all, wrap your use of the StreamWriter in a using block so that it's disposed for you.


Also, if you are not wanting to close the file. You could use flush.


ReadLine() returns an empty string when the line doesn't contain any characters... Call Flush() and Close() ... consider using using...

Why aren't you just copying the file as a whole (File.Copy) ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜