Stream.CopyTo - 文件为空。 ASP.NET
我使用以下代码保存上传的图像:
using (var fileStream = File.Create(savePath))
{
stream.CopyTo(fileStream);
}
当图像保存到目标文件夹时,它是空的,0 kb。这里可能出了什么问题?我在复制之前检查了stream.Length,它不为空。
I'm saving an uploaded image using this code:
using (var fileStream = File.Create(savePath))
{
stream.CopyTo(fileStream);
}
When the image is saved to its destination folder, it's empty, 0 kb. What could possible be wrong here? I've checked the stream.Length before copying and its not empty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的代码没有任何问题。您说“我在复制之前检查了stream.Length并且它不为空”这一事实让我想知道复制之前的流位置。
如果您已经使用过源流一次,那么尽管流的长度不是零,但它的位置可能位于流的末尾 - 因此没有什么可以复制的。
如果流是可查找的(对于
MemoryStream
或FileStream
等),请尝试将其放在副本之前。这会将流位置重置为开头,这意味着您的代码将复制整个流。
There is nothing wrong with your code. The fact you say "I've checked the stream.Length before copying and its not empty" makes me wonder about the stream position before copying.
If you've already consumed the source stream once then although the stream isn't zero length, its position may be at the end of the stream - so there is nothing left to copy.
If the stream is seekable (which it will be for a
MemoryStream
or aFileStream
and many others), try puttingjust before the copy. This resets the stream position to the beginning, meaning the whole stream will be copied by your code.
我建议将以下内容放在
CopyTo()
之前,并确保在此之后使用
Flush()
,以避免复制后出现空文件。I would recommend to put the following before
CopyTo()
Make sure to use the
Flush()
after this, to avoid empty file after copy.在将我的项目从 .NET Core 1 迁移到 2.2 后,这个问题就开始出现了。
我通过将文件流的
Position
设置为零来解决此问题。This problem started for me after migrating my project from to .NET Core 1 to 2.2.
I fixed this issue by setting the
Position
of my filestream to zero.包含 FileAccess 和 FileShare 尤其是当路径是 NFS/CIFS
文件流构造函数(系统.IO) | Microsoft Learn)
FileStream(String, FileMode, FileAccess, FileShare)
UnauthorizedAccessException
对于指定的路径,操作系统不允许所请求的访问,例如
It would help to include the FileAccess and FileShare especially if the path is an NFS/CIFS
FileStream Constructor (System.IO) | Microsoft Learn)
FileStream(String, FileMode, FileAccess, FileShare)
UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified path, such as