ASP.NET、Streamwriter、Filestream - 0 字节文件
这有效:
using (StreamWriter stw = new StreamWriter(Server.MapPath("\\xml\\file.xml")))
{
stw.Write(xmlEncStr);
}
这会创建一个空文件:
using (FileStream file = new FileStream(Server.MapPath("\\xml\\file.xml"), FileMode.CreateNew))
{
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(xmlEncStr);
}
}
我尝试使用 FileStream 构造函数并尝试刷新,但仍然得到一个零字节文件。我正在编写的字符串是一个简单的base64编码的ascii字符串,没有特殊字符。
我知道我可以使用第一个示例,但为什么第二个示例不起作用?
更新
这不是 Filestream/StreamWriter 问题 - 这是变量命名问题。我更正了上面的代码,所以现在两个版本都可以工作。我原来有:
StreamWriter strw = new StreamWriter(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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以稍微缩短代码:
MapPath
方法还接受相对路径或虚拟路径,并将其转换为服务器上相应的物理路径。\\xml\\file.xml
不是以上内容。它可能应该是:~/xml/file.xml
。You could shorten your code a bit:
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
.不可重现。
这不应该是 ASP.NET 问题,第二种形式应该可以工作(提供 sw==strw )。
但是,如果文件已存在,
FileMode.CreateNew
将会失败,因此,如果您使用固定的文件名,并且如果它是在之前的尝试中作为空文件创建的,那么这就可以解释症状。但@Darin Dimitrov 提供了更好的选择。
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.