简体   繁体   中英

Why doesn't FileStream as an argument to Streamwriter write to text file?

In the code included below, I am able to write the contents of the string 'fullname' to a text file in the specified directory when using the following statement: System.IO.File.WriteAllText(path, fullname); However, if I write the string path to a FileStream object (withe arguments specified), and then pass that FileStream object as an argument to the StreamWriter object, the file is created, but no contents are written.

First attempt: Comment out System.IO.File.WriteAllText(path, fullname); and use the three lines above it. This creates the file but no contents are written into the file.

Second attempt: Un-comment the System.IO.File.WriteAllText(path, fullname); statement and comment the three lines above it. This executes as desired.

Here is the full block of code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use the Split() method of the String Class
            string fullname = " Robert Gordon Orr ";
            fullname = fullname.Trim();
            string[] splitNameArray = fullname.Split(' ');
            Console.WriteLine("First Name is: {0}", splitNameArray[0]);
            Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
            Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
            Console.WriteLine("Full name is: {0}", fullname);
            string path = @"C:\Programming\C#\C# Practice Folder\Console Applications\FileInputOutput\textfile.txt";

            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            StreamWriter toFile = new StreamWriter(fs);
            toFile.Write(fullname);

            //System.IO.File.WriteAllText(path, fullname);`enter code here`

            Console.ReadLine();

        }
    }
}

As others have said: streams must be flushed in .NET in order for them to write to disk. This can be done manually, however I would simply change your code to have using statements on your streams:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use the Split() method of the String Class
            string fullname = " Robert Gordon Orr ";
            fullname = fullname.Trim();
            string[] splitNameArray = fullname.Split(' ');
            Console.WriteLine("First Name is: {0}", splitNameArray[0]);
            Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
            Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
            Console.WriteLine("Full name is: {0}", fullname);
            string path = @"C:\textfile.txt";

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                using (StreamWriter toFile = new StreamWriter(fs))
                {
                    toFile.Write(fullname);
                }
            }
            //System.IO.File.WriteAllText(path, fullname);`enter code here`

            Console.ReadLine();

        }
    }
}

Calling Dispose() on a stream (as using implicitly does), causes the stream to be flushed and closed at the end of the using block.

I think you are just forgetting to flush your file stream:

fs.Flush();

This is needed because according to msdn, this is what makes the FileStream to actually write the buffer to the file.

Flush: Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush().)

Regards.

From MSDN on StreamWriter

You must call Close to ensure that all data is correctly written out to the underlying stream.

So the problem here is mainly that, since you don't actually close the StreamWriter, the data gets backed up but doesn't push to the file, even though the FileStream immediately created the file in its constructor. Never ever forget to close your stream, as failing to do so could lead to major problems down the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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