简体   繁体   English

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

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

I am trying to convert a document in a SharePoint document library to byte array in restful WCF service. 我正在尝试将SharePoint文档库中的文档转换为静态WCF服务中的字节数组。 When I declared the byte array with the maximum size, i am getting the files size as the maximum that I had declared. 当我声明最大大小的字节数组时,我得到的文件大小是我声明的最大大小。 I need to know how to declare the byte array dynamically. 我需要知道如何动态声明字节数组。

Below is my code: 下面是我的代码:

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);

    }
}

I got the solution from the below link 我从下面的链接获得了解决方案

http://ranaictiu-technicalblog.blogspot.co.uk/2010/06/sharepoint-2010-attach-files-to.html 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();

Your buffer doesn't need to be the same size as the file at all. 您的缓冲区根本不需要与文件大小相同。 You're only using it as temporary storage, to copy a chunk of the input file into your output MemoryStream . 您仅将其用作临时存储,将输入文件的一部分复制到输出MemoryStream

I'd personally use something like 16K as the size - not big enough to end up in the large object heap, but not so small that you end up with lots of tiny IO operations. 我个人会使用16K之类的大小-大小不足以容纳大型对象堆,但又不能太小以至于您最终会进行许多微小的IO操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM