上传到SharePoint在线库C# [英] Upload to SharePoint online Library C#
问题描述
您好
我正在尝试创建一个webform,将包含元数据的文档上传到sharepoint库
我的库是带有Titel,Name,Aftername,E-Mail的文档库。
我的表单有3个文本字段和一个上传组件
我如何上传我的共享点有3个文本字段的文件
我尝试使用此功能但没有成功。
public void SaveFileToSharePoint(string fileName)
      {
          using(var context = new ClientContext(" URL")))
          {
              var passWord = new SecureString();
              foreach(var c in"password")passWord.AppendChar(c);
              context.Credentials = new SharePointOnlineCredentials(" myLogin",passWord);
              var web = context.Web;
              var newFile = new FileCreationInformation {Content = File.ReadAllBytes(fileName),Url = Path.GetFileName(fileName)};
              var docs = web.Lists.GetByTitle(" Upload");
              docs.RootFolder.Folders.GetByUrl(" Test")。Files.Add(newFile);
              context.ExecuteQuery();
          }¥b $ b       }
谢谢
您好,
示例代码供您参考。
public static Microsoft.SharePoint.Client.File UploadFileSlicePerSlice(ClientContext ctx,string libraryName,string fileName,int fileChunkSizeInMB = 3)
{
//每个切片上传都需要一个唯一的ID。
Guid uploadId = Guid.NewGuid();
//获取文件的名称。
string uniqueFileName = Path.GetFileName(fileName);
//确保目标库存在,如果缺少则创建它。
// if(!LibraryExists(ctx,ctx.Web,libraryName))
// {
// CreateLibrary(ctx,ctx.Web,libraryName);
//}
//获取要上传的文件夹。
列出docs = ctx.Web.Lists.GetByTitle(libraryName);
ctx.Load(docs,l => l.RootFolder);
//获取有关保存文件的文件夹的信息。
ctx.Load(docs.RootFolder,f => f.ServerRelativeUrl);
ctx.ExecuteQuery();
//文件对象。
Microsoft.SharePoint.Client.File uploadFile;
//计算块大小(以字节为单位)。
int blockSize = fileChunkSizeInMB * 1024 * 1024;
//获取有关保存文件的文件夹的信息。
ctx.Load(docs.RootFolder,f => f.ServerRelativeUrl);
ctx.ExecuteQuery();
//获取文件的大小。
long fileSize = new FileInfo(fileName).Length;
if(fileSize< = blockSize)
{
//使用常规方法。
using(FileStream fs = new FileStream(fileName,FileMode.Open))
{
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.ContentStream = fs;
fileInfo.Url = uniqueFileName;
fileInfo.Overwrite = true;
uploadFile = docs.RootFolder.Files.Add(fileInfo);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
//返回上传文件的文件对象。
返回uploadFile;
}
}
else
{
//使用大文件上传方法。
ClientResult< long> bytesUploaded = null;
FileStream fs = null;
try
{
fs = System.IO.File.Open(fileName,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
using(BinaryReader br = new BinaryReader(fs))
{
byte [] buffer = new byte [blockSize];
Byte [] lastBuffer = null;
long fileoffset = 0;
long totalBytesRead = 0;
int bytesRead;
bool first = true;
bool last = false;
//以块为单位从文件系统中读取数据。
while((bytesRead = br.Read(buffer,0,buffer.Length))> 0)
{
totalBytesRead = totalBytesRead + bytesRead;
//你已经到了文件的末尾。
if(totalBytesRead == fileSize)
{
last = true;
//复制到具有正确大小的新缓冲区。
lastBuffer = new byte [bytesRead];
Array.Copy(buffer,0,lastBuffer,0,bytesRead);
}
if(first)
{
using(MemoryStream contentStream = new MemoryStream())
{
//添加空文件。
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.ContentStream = contentStream;
fileInfo.Url = uniqueFileName;
fileInfo.Overwrite = true;
uploadFile = docs.RootFolder.Files.Add(fileInfo);
//通过上传第一个切片开始上传。
using(MemoryStream s = new MemoryStream(buffer))
{
//在第一个切片上调用start upload方法。
bytesUploaded = uploadFile.StartUpload(uploadId,s);
ctx.ExecuteQuery();
// fileoffset是将添加下一个切片的指针。
fileoffset = bytesUploaded.Value;
}
//您只能开始上传一次。
first = false;
}
}
else
{
//获取对您文件的引用。
uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);
if(last)
{
//这是最后一片数据吗?
using(MemoryStream s = new MemoryStream(lastBuffer))
{
//通过调用FinishUpload结束切片上传。
uploadFile = uploadFile.FinishUpload(uploadId,fileoffset,s);
ctx.ExecuteQuery();
//返回上传文件的文件对象。
返回uploadFile;
}
}
else
{
使用(MemoryStream s = new MemoryStream(buffer))
{
//继续切片上传。
bytesUploaded = uploadFile.ContinueUpload(uploadId,fileoffset,s);
ctx.ExecuteQuery();
//更新下一个切片的文件偏移量。
fileoffset = bytesUploaded.Value;
}
}
}
} // while((bytesRead = br.Read(buffer,0,buffer.Length))> 0)
$
}
最后
{
if(fs!= null)
{
fs.Dispose();
}
}
}
返回null;
}
static void Main(string [] args)
{
string _SiteUrl =" https://tenant.sharepoint.com/sites/tst" ;;
using(var clientContext = new ClientContext(_SiteUrl))
{
Console.ForegroundColor = ConsoleColor.Green;
string password =" pw" ;;
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(),sec_pass.AppendChar);
sec_pass.MakeReadOnly();
clientContext.Credentials = new SharePointOnlineCredentials(" lee@tenant.onmicrosoft.com",sec_pass);
string libraryName =" MyDoc3" ;;
string fileName = @" C:\Lee \ListData.csv" ;;
var file = UploadFileSlicePerSlice(clientContext,libraryName,fileName);
var item = file.ListItemAllFields;
//这里的字段和值
item [" testColom"] =" test value" ;;
item.Update();
clientContext.ExecuteQuery();
Console.WriteLine(" done");
Console.ReadKey();
}
}参考下面的官方演示代码,我评论LibraryExists如果你需要它,你可以实现它。
最诚挚的问候,
利跨度>
Hi
I am trying to create a webform to upload a document with metadata to sharepoint library
My library is a document library with Titel, Name, Aftername, E-Mail.
My form has 3 text fields and a upload component
How can i upload the file with 3 textfields to my sharepoint
i have try to use this but without success.
public void SaveFileToSharePoint(string fileName){
using (var context = new ClientContext("URL"))
{
var passWord = new SecureString();
foreach (var c in "password") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("myLogin", passWord);
var web = context.Web;
var newFile = new FileCreationInformation { Content = File.ReadAllBytes(fileName), Url = Path.GetFileName(fileName) };
var docs = web.Lists.GetByTitle("Upload");
docs.RootFolder.Folders.GetByUrl("Test").Files.Add(newFile);
context.ExecuteQuery();
}
}
Thanks
Hi,
Sample code for your reference.
public static Microsoft.SharePoint.Client.File UploadFileSlicePerSlice(ClientContext ctx, string libraryName, string fileName, int fileChunkSizeInMB = 3) { // Each sliced upload requires a unique ID. Guid uploadId = Guid.NewGuid(); // Get the name of the file. string uniqueFileName = Path.GetFileName(fileName); // Ensure that target library exists, and create it if it is missing. //if (!LibraryExists(ctx, ctx.Web, libraryName)) //{ // CreateLibrary(ctx, ctx.Web, libraryName); //} // Get the folder to upload into. List docs = ctx.Web.Lists.GetByTitle(libraryName); ctx.Load(docs, l => l.RootFolder); // Get the information about the folder that will hold the file. ctx.Load(docs.RootFolder, f => f.ServerRelativeUrl); ctx.ExecuteQuery(); // File object. Microsoft.SharePoint.Client.File uploadFile; // Calculate block size in bytes. int blockSize = fileChunkSizeInMB * 1024 * 1024; // Get the information about the folder that will hold the file. ctx.Load(docs.RootFolder, f => f.ServerRelativeUrl); ctx.ExecuteQuery(); // Get the size of the file. long fileSize = new FileInfo(fileName).Length; if (fileSize <= blockSize) { // Use regular approach. using (FileStream fs = new FileStream(fileName, FileMode.Open)) { FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = fs; fileInfo.Url = uniqueFileName; fileInfo.Overwrite = true; uploadFile = docs.RootFolder.Files.Add(fileInfo); ctx.Load(uploadFile); ctx.ExecuteQuery(); // Return the file object for the uploaded file. return uploadFile; } } else { // Use large file upload approach. ClientResult<long> bytesUploaded = null; FileStream fs = null; try { fs = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (BinaryReader br = new BinaryReader(fs)) { byte[] buffer = new byte[blockSize]; Byte[] lastBuffer = null; long fileoffset = 0; long totalBytesRead = 0; int bytesRead; bool first = true; bool last = false; // Read data from file system in blocks. while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead = totalBytesRead + bytesRead; // You've reached the end of the file. if (totalBytesRead == fileSize) { last = true; // Copy to a new buffer that has the correct size. lastBuffer = new byte[bytesRead]; Array.Copy(buffer, 0, lastBuffer, 0, bytesRead); } if (first) { using (MemoryStream contentStream = new MemoryStream()) { // Add an empty file. FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = contentStream; fileInfo.Url = uniqueFileName; fileInfo.Overwrite = true; uploadFile = docs.RootFolder.Files.Add(fileInfo); // Start upload by uploading the first slice. using (MemoryStream s = new MemoryStream(buffer)) { // Call the start upload method on the first slice. bytesUploaded = uploadFile.StartUpload(uploadId, s); ctx.ExecuteQuery(); // fileoffset is the pointer where the next slice will be added. fileoffset = bytesUploaded.Value; } // You can only start the upload once. first = false; } } else { // Get a reference to your file. uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName); if (last) { // Is this the last slice of data? using (MemoryStream s = new MemoryStream(lastBuffer)) { // End sliced upload by calling FinishUpload. uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s); ctx.ExecuteQuery(); // Return the file object for the uploaded file. return uploadFile; } } else { using (MemoryStream s = new MemoryStream(buffer)) { // Continue sliced upload. bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s); ctx.ExecuteQuery(); // Update fileoffset for the next slice. fileoffset = bytesUploaded.Value; } } } } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) } } finally { if (fs != null) { fs.Dispose(); } } } return null; } static void Main(string[] args) { string _SiteUrl = "https://tenant.sharepoint.com/sites/tst"; using (var clientContext = new ClientContext(_SiteUrl)) { Console.ForegroundColor = ConsoleColor.Green; string password = "pw"; SecureString sec_pass = new SecureString(); Array.ForEach(password.ToArray(), sec_pass.AppendChar); sec_pass.MakeReadOnly(); clientContext.Credentials = new SharePointOnlineCredentials("lee@tenant.onmicrosoft.com", sec_pass); string libraryName = "MyDoc3"; string fileName=@"C:\Lee\ListData.csv"; var file =UploadFileSlicePerSlice(clientContext, libraryName, fileName); var item=file.ListItemAllFields; //your fields and value here item["testColom"]="test value"; item.Update(); clientContext.ExecuteQuery(); Console.WriteLine("done"); Console.ReadKey(); } }Reference the code from below official demo, I comment LibraryExists logic, you could achieve it if you need it.
Best Regards,
Lee
这篇关于上传到SharePoint在线库C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!