如何在 C# 中为大文件动态声明字节数组

How to declare byte array dynamically in c# for large files

我正在尝试将 SharePoint 文档库中的文档转换为 restful WCF 服务中的字节数组。当我声明具有最大大小的字节数组时,我得到的文件大小是我声明的最大值。我需要知道如何动态声明字节数组。

下面是我的代码:

using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
    DocumentID = "229"; 
    clientContext.Credentials = new System.Net.NetworkCredential(@"username", "pwd", "domain");
    CSOM.Web _Site = clientContext.Web;
    CSOM.List _List = _Site.Lists.GetByTitle("TestFiles");
    CSOM.ListItem listItem = _List.GetItemById(Convert.ToInt32(DocumentID));
    clientContext.Load(_List);
    clientContext.Load(listItem, i => i.File);
    clientContext.ExecuteQuery();           
    var fileRef = listItem.File.ServerRelativeUrl;
    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
    byte[] buffer = new byte[9469417];
    // how to declare the above byte array dynamically with the file size dynamically
    using (MemoryStream memoryStream = new MemoryStream())
    {

        int bytesRead;
        do
        {
            bytesRead = fileInfo.Stream.Read(buffer, 0, buffer.Length);
            memoryStream.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);

        string base64 = Convert.ToBase64String(buffer);

    }
}

您的缓冲区根本不需要与文件大小相同。您仅将其用作临时存储,将输入文件的 复制到输出 MemoryStream.

我个人会使用 16K 之类的大小 - 不会大到最终出现在大型对象堆中,但也不会小到导致大量微小的 IO 操作结束。

我从下面得到了解决方案link

http://ranaictiu-technicalblog.blogspot.co.uk/2010/06/sharepoint-2010-attach-files-to.html

               var fileRef = listItem.File.ServerRelativeUrl;
              var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
                var stream = fileInfo.Stream;
                IList<byte> content = new List<byte>();
                int b;
                while ((b = fileInfo.Stream.ReadByte()) != -1)
                {
                    content.Add((byte)b);
                }
                byte[] barray = content.ToArray();