Как получить размер файла из объекта Microsoft.SharePoint.Client.File?
Я ищу хороший способ получить размер файла из Microsoft.SharePoint.Client.File
объект.
Client
объект не имеет Length
член.
Я попробовал это:
foreach (SP.File file in files)
{
string path = file.Path;
path = path.Substring(this.getTeamSiteUrl().Length);
FileInformation fileInformation = SP.File.OpenBinaryDirect(this.Context, path);
using (MemoryStream memoryStream = new MemoryStream())
{
CopyStream(fileInformation.Stream, memoryStream);
file.Size = memoryStream.Length;
}
}
Что дало мне длину с помощью MemoryStream
, но это не хорошо для производительности. Этот файл также не принадлежит библиотеке документов. Поскольку это прикрепленный файл, я не могу преобразовать его в ListItem
использование объекта ListItemAllFields
, Если бы я мог преобразовать его в ListItem
Я мог бы получить его размер, используя: ListItem["File_x0020_Size"]
Как я могу получить размер файла Client
объект в SharePoint с использованием C#?
3 ответа
Загрузите File_x0020_Size
информация о поле, чтобы получить его.
Вот что я делаю, когда хочу перечислить все файлы в папке Sharepoint 2010:
//folderPath is something like /yoursite/yourlist/yourfolder
Microsoft.SharePoint.Client.Folder spFolder = _ctx.Web.GetFolderByServerRelativeUrl(folderPath);
_ctx.Load(spFolder);
_ctx.ExecuteQuery();
FileCollection fileCol = spFolder.Files;
_ctx.Load(fileCol);
_ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.File spFile in fileCol)
{
//In here, specify all the fields you want retrieved, including the file size one...
_ctx.Load(spFile, file => file.Author, file => file.TimeLastModified, file=>file.TimeCreated,
file => file.Name, file => file.ServerRelativeUrl, file => file.ListItemAllFields["File_x0020_Size"]);
_ctx.ExecuteQuery();
int fileSize = int.Parse((string)spFile.ListItemAllFields["File_x0020_Size"]);
}
_ctx
очевидно, ClientContext
Вы инициировали.
Вот расширенный список всех внутренних полей Sharepoint
Я не знаю, был ли когда-нибудь решен этот вопрос, но для людей, которые ищут ответ (как я сделал):
... КОД ДЛЯ ПОЛУЧЕНИЯ SP.FILE...
SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(ctx, mySPFile.ServerRelativeUrl);
byte[] bodyString = ReadToEnd(fileInfo.Stream);
int length = bodyString.Length;
Console.Write(length.ToString());
... ДЕЛАТЬ ДРУГОЙ ХАРАКТЕР, КОТОРЫЙ ВЫ ДОЛЖНЫ ДЕЛАТЬ....
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = 0;
if (stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
Надеюсь, что это поможет другим людям, потому что я не мог найти прямой ответ в Интернете!
Разве вы не можете просто использовать длину свойства Stream?
file.Size = fileInformation.Stream.Length;