将pdf流保存为pdf文件

时间:2020-04-30 06:23:18

标签: c# .net file pdf stream

我有一个保存pdf流的变量,该变量的类型为System.Threading.Tasks.Task<Stream>。我想将此pdf流保存为pdf文件,但不确定如何保存。以下是我尝试处理的一段代码。关于如何尝试将此流保存到文件中的任何想法

System.Threading.Tasks.Task<Stream> pdf = //Some logic here which gets a pdf stream

我想将pdf内容作为pdf存储在文件的变量中

为此,我赞扬了方法

public static void SaveStreamAsFile(string filePath, System.Threading.Tasks.Task<Stream> inputStream, string fileName)
{

    string path = Path.Combine(filePath, fileName);
    using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
    {
       // logic
    }
}

1 个答案:

答案 0 :(得分:1)

读取输入流并将其写入输出流。

public static async Task SaveStreamAsFile(string filePath, System.Threading.Tasks.Task<Stream> inputStream, string fileName)
{
    var stream = await inputStream;
    var path = Path.Combine(filePath, fileName);
    var bytesInStream = new byte[stream.Length];

    await stream.ReadAsync(bytesInStream, 0, (int) bytesInStream.Length);

    using (var outputFileStream = new FileStream(path, FileMode.Create))
    {
       await outputFileStream.WriteAsync(bytesInStream, 0, bytesInStream.Length);
    }
}
相关问题