【发布时间】:2020-06-27 08:11:08
【问题描述】:
我想获取文件并将其作为流传递,但我不确定如何执行此操作。我确实有文件所在的路径。所以基本上使用这个路径,我将检索这个文件并将其保存为流。但是,如果我错了,请纠正我,但是假设“作为流读取”就像它实际上是在打开文件并读取它一样正确吗?
是否有只是将文件检索或复制到 FileStream 或 MemoryStream 中?现在我有这个但不确定这是否正确
foreach (string filePath in filePaths)
{
string filename = Path.GetFileName(filePath);
//Constants.Conventions.MediaTypes.Image
string mediaType = Constants.Conventions.MediaTypes.File;
string ext = Path.GetExtension(filename);
IMedia media = Services.MediaService.CreateMedia(filename, Constants.System.Root, mediaType);
MemoryStream ms = new MemoryStream();
using (Stream stream = System.IO.File.OpenRead(filePath))
{
ms.WriteTo(stream);
}
media.SetValue("umbracoFile", filename, ms);
// Save the media
Services.MediaService.Save(media);
media = null;
System.IO.File.Delete(filePath);
}
我不太确定这是否是最好的方法。但主要目标是从路径中检索该文件并将其保存在media.SetValue("umbracoFile", filename, ms); 中,因为它需要Stream 作为输入。我如何以最有效的方式做到这一点?由于大文件,我总是遇到内存不足异常。所以我猜是因为它将它作为 Stream 读取它会在大文件上引发错误。所以也许我们可以复制它来保存。我不太确定这里真的需要帮助
更新: 这是确保我不会耗尽内存的配置
<httpRuntime requestValidationMode="2.0" enableVersionHeader="false" maxRequestLength="2097151" executionTimeout="50000000" targetFramework="4.5" fcnMode="Single" />
<location path="umbraco">
<system.web>
<httpRuntime maxRequestLength="204800" executionTimeout="99999"/>
</system.web>
</location>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2294967295" />
</requestFiltering>
</security>
这是我项目的构建
【问题讨论】:
-
您是否正在为 64 位编译您的应用程序?这将大大增加您可以使用的内存量。
-
是的,已经这样做了
-
请注意,.net 在编译属性中有一个非常愚蠢的选项“首选 32 位”,如果启用它,即使您为 x64 编译它也会以 32 位模式运行程序。此外,如果它在 IIS 下运行,请检查它是否在 64 位模式下执行。
-
@Gusman 你能检查我的设置是否正确吗?我基本上将其更改为 x64,但在处理 1.6GB 文件时仍然出现 OutOfMemoryException 错误
-
是的,看来你已经配置好了...