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?
Up开发者_运维知识库date
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.
精彩评论