将PDF转换为字节

时间:2012-10-05 06:13:51

标签: c# .net wcf

我有一个WCF服务,用于存储用户上传到文件服务器的文档(PDF文件)。现在,我想将这些PDF文件转换为字节,以便iOS客户端可以在iPad上下载它们。我不想将PDF存储为SQL中的BLOB,只需转换为字节并将其发送到iPad。任何链接/示例代码都非常感谢。

2 个答案:

答案 0 :(得分:7)

您可以简单地将PDF文件读取为字节数组:

byte[] bytes = System.IO.File.ReadAllBytes(pathToFile);

答案 1 :(得分:1)

你可以这样做:

public byte[] ReadPDF(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;  // sum is a buffer offset for next reading
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }