将FIlestream复制到新流中,得到空文件

时间:2019-03-15 11:52:37

标签: c# stream filestream

我正在转换一些文件,但是在第二步时遇到了一些问题。

  1. 从源位置加载文件
  2. 将文件保存到临时文件夹
  3. 将转换后的文件保存到输出位置

我有2种读取原始文件的方法,但是两者都有问题。

  • 方法1:文件保持锁定状态(因此当出现问题时,我必须重新启动应用程序)
  • 方法2:临时文件为空

有人知道如何解决其中一个问题吗?

实用程序类

/// <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
}

2 个答案:

答案 0 :(得分:0)

为了将源文件复制到临时文件夹,最简单的方法是使用File.Copy名称空间中的System.IO方法。请考虑以下内容:

// Assuming the variables have been set as you already had, this creates a copy in the intended location.
File.Copy(documentLocation, filename);

答案 1 :(得分:0)

进一步挖掘之后。我发现您可以在File.Open中添加一个属性,以“修复”此问题:

return File.Open(documentLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

缺点是您仍然无法移动/重命名文件,但是锁已被删除。