简体   繁体   中英

ASP.NET, Streamwriter, Filestream - 0 byte file

This works:

using (StreamWriter stw = new StreamWriter(Server.MapPath("\\xml\\file.xml")))
{
    stw.Write(xmlEncStr);
}

This creates an empty file:

using (FileStream file = new FileStream(Server.MapPath("\\xml\\file.xml"), FileMode.CreateNew))
{
    using (StreamWriter sw = new StreamWriter(file))
    {
        sw.Write(xmlEncStr);
    }
}

I tried playing around with the FileStream constructor and tried flushing and I still get a zero byte file. The string I am writing is a simple base64 encoded ascii string with no special characters.

I know I can use the first example, but why won't the second work?

Update

This wasn't a Filestream/StreamWriter problem - it was a variable naming problem. I corrected the code above, so now both versions work. I originally had:

StreamWriter strw = new StreamWriter(file)

You could shorten your code a bit:

File.WriteAllText(Server.MapPath("\\xml\\file.xml"), xmlEncStr);

Also the MapPath method accepts a relative or virtual path and converts it to the corresponding physical path on the server. \\\\xml\\\\file.xml is non of the above. It probably should be: ~/xml/file.xml .

Not reproducable.

It shouldn't be an ASP.NET issue and the second form ought to work (provided sw==strw ).

But FileMode.CreateNew will fail if the file already exists, so if you use a fixed filename, and if it was created during an earlier attempt as an empty file then that would explain the symptoms.

But @Darin Dimitrov provides a better alternative.

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