【发布时间】:2019-03-15 11:52:37
【问题描述】:
我正在转换一些文件,但我在第二步遇到了一些问题。
- 从源位置加载文件
- 将文件保存到临时文件夹
- 将转换后的文件保存到输出位置
我有两种读取原始文件的方法,但它们都有问题。
- 方法1:文件保持锁定状态(所以当出现问题时,我必须重新启动应用程序)
- 方法二:临时文件为空
有人知道如何解决其中一个问题吗?
实用程序类
/// <summary>
/// Get document stream
/// </summary>
/// <param name="DocumentName">Input document name</param>
public static Stream GetDocumentStreamFromLocation(string documentLocation)
{
try
{
//ExStart:GetDocumentStream
// Method one: works, but locks file
return File.Open(documentLocation, FileMode.Open, FileAccess.Read);
// Method two: gives empty file on temp folder
using (FileStream fsSource = File.Open(documentLocation, FileMode.Open, FileAccess.Read))
{
var stream = new MemoryStream((int)fsSource.Length);
fsSource.CopyTo(stream);
return stream;
}
//ExEnd:GetDocumentStream
}
catch (FileNotFoundException ioEx)
{
Console.WriteLine(ioEx.Message);
return null;
}
}
/// <summary>
/// Save file in any format
/// </summary>
/// <param name="filename">Save as provided string</param>
/// <param name="content">Stream as content of a file</param>
public static void SaveFile(string filename, Stream content, string location = OUTPUT_PATH)
{
try
{
//ExStart:SaveAnyFile
//Create file stream
using (FileStream fileStream = File.Create(Path.Combine(Path.GetFullPath(location), filename)))
{
content.CopyTo(fileStream);
}
//ExEnd:SaveAnyFile
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
我调用如下函数如下:
public static StreamContent Generate(string sourceLocation)
{
// Get filename
var fileName = Path.GetFileName(sourceLocation);
// Create tempfilename
var tempFilename = $"{Guid.NewGuid()}_{fileName}";
// Put file in storage location
Utilities.SaveFile(tempFilename, Utilities.GetDocumentStreamFromLocation(sourceLocation), Utilities.STORAGE_PATH);
// ... More code
}
【问题讨论】:
-
在开始
CopyTo之前尝试fsSource.Seek(0, SeekOrigin.Begin);。 IIRC Open 方法将 Seek 位置指向文件末尾。 -
复制前是否需要对数据进行任何处理?例如,您是在处理源的副本还是流本身?
-
@Fabulous 我正在处理文档的副本
-
@MarkusDeibel 没用
-
为了制作副本,我建议使用
File.Copy(string, string)方法,它会为您制作副本,然后您可以打开该流并进行处理。
标签: c# stream filestream