コード例 #1
0
        public async Task UploadFile(string filePath, string folderId)
        {
            var client = await this.AuthenticationHelper
                         .EnsureSharePointClientCreatedAsync(
                Office365Capabilities.MyFiles.ToString());

            client.Context.IgnoreMissingProperties = true;

            string filename = System.IO.Path.GetFileName(filePath);

            using (FileStream fileStream = System.IO.File.OpenRead(filePath))
            {
                SPOFileServices.File file = new SPOFileServices.File()
                {
                    Name = filename
                };
                if (!String.IsNullOrEmpty(folderId))
                {
                    await client.Files.GetById(folderId).ToFolder().Children.AddItemAsync(file);
                }
                else
                {
                    await client.Files.AddItemAsync(file);
                }
                await client.Files.GetById(file.Id).ToFile().UploadAsync(fileStream);
            }
        }
コード例 #2
0
    public async Task<File> UploadFile(System.IO.Stream filestream, string filename) {
      var client = await EnsureClientCreated();

      File newFile = new File {
        Name = filename        
      };

      // create the entry for the file
      await client.Files.AddItemAsync(newFile);
      await client.Files.GetById(newFile.Id).ToFile().UploadAsync(filestream);

      return newFile;
    }
コード例 #3
0
        //<summary>
        //Creates a new file named demo.txt in the default document library.
        //</summary>
        //<returns>A Boolean value that indicates whether the new text file was successfully created.</returns>
        internal async Task <String> CreateNewTextFileAsync()
        {
            //bool isSuccess = false;
            String newID            = string.Empty;
            var    sharePointClient = await AuthenticationHelper.EnsureSharePointClientCreatedAsync("MyFiles");

            try
            {
                // First check whether demo.txt already exists. If it exists, delete it.
                // If it doesn't exist, swallow the error.
                IItem item = await sharePointClient.Files.GetByPathAsync("demo.txt");

                await item.DeleteAsync();
            }
            catch (ODataErrorException)
            {
                // fail silently because demo.txt doesn't exist.
            }

            try
            {
                // In this example, we'll create a simple text file and write the current timestamp into it.
                string createdTime = "Created at " + DateTime.Now.ToLocalTime().ToString();
                byte[] bytes       = Encoding.UTF8.GetBytes(createdTime);

                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    // File is called demo.txt. If it already exists, we'll get an exception.
                    Microsoft.Office365.SharePoint.FileServices.File newFile = new Microsoft.Office365.SharePoint.FileServices.File
                    {
                        Name = "demo.txt"
                    };

                    // Create the empty file.
                    await sharePointClient.Files.AddItemAsync(newFile);

                    newID = newFile.Id;

                    // Upload the file contents.
                    await sharePointClient.Files.GetById(newFile.Id).ToFile().UploadAsync(stream);
                }
            }

            // ODataErrorException can be thrown when you try to create a file that already exists.
            catch (Microsoft.Data.OData.ODataErrorException)
            {
                //isSuccess = false;
            }

            return(newID);
        }
コード例 #4
0
        /// <summary>
        /// Reads the contents of a text file and displays the results in a TextBox.
        /// </summary>
        /// <param name="_selectedFileObject">The file selected in the ListBox.</param>
        /// <returns>A Boolean value that indicates whether the text file was successfully read.</returns>
        internal async Task <object[]> ReadTextFileAsync(string selectedItemID)
        {
            string fileContents = string.Empty;

            object[] results = new object[] { fileContents, false };

            try
            {
                // Make sure we have a reference to the SharePoint client
                var spClient = await AuthenticationHelper.EnsureSharePointClientCreatedAsync("MyFiles");

                // Get a handle on the selected item.
                IItemFetcher thisItemFetcher = spClient.Files.GetById(selectedItemID);
                IFileFetcher thisFileFetcher = thisItemFetcher.ToFile();
                var          myFile          = await thisFileFetcher.ExecuteAsync();

                // Check that the selected item is a .txt file.
                if (!myFile.Name.EndsWith(".txt") && !myFile.Name.EndsWith(".xml"))
                {
                    results[0] = string.Empty;
                    results[1] = false;
                    return(results);
                }

                Microsoft.Office365.SharePoint.FileServices.File file = myFile as Microsoft.Office365.SharePoint.FileServices.File;

                // Download the text file and put the results into a string. This results in a call to the service.
                using (Stream stream = await file.DownloadAsync())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        results[0] = await reader.ReadToEndAsync();

                        results[1] = true;
                    }
                }
            }
            catch (NullReferenceException)
            {
                results[1] = false;
            }
            catch (ArgumentException)
            {
                results[1] = false;
            }

            return(results);
        }
コード例 #5
0
        internal async Task <bool> DownloadFileAsync(string selectedItemID)
        {
            var results = false;

            try
            {
                // Make sure we have a reference to the SharePoint client
                var spClient = await AuthenticationHelper.EnsureSharePointClientCreatedAsync("MyFiles");

                // Get a handle on the selected item.
                IItemFetcher thisItemFetcher = spClient.Files.GetById(selectedItemID);
                IFileFetcher thisFileFetcher = thisItemFetcher.ToFile();
                var          myFile          = await thisFileFetcher.ExecuteAsync();

                Microsoft.Office365.SharePoint.FileServices.File file = myFile as Microsoft.Office365.SharePoint.FileServices.File;

                // Download the file and put the results into a string. This results in a call to the service.
                using (Stream stream = await file.DownloadAsync())
                {
                    // TODO: save file to users locker
                    // Create a new file. If the file already exists, it will be overwritten.
                    using (var fileStream = new FileStream(@"C:\hosting\WebApp1\Downloads\" + myFile.Name, FileMode.Create, FileAccess.Write))
                    {
                        stream.CopyTo(fileStream);
                    }
                }

                results = true;
            }
            catch (Exception exc)
            {
                throw new Exception("Error occured while downloading file:  ", exc);
            }

            return(results);
        }
        //<summary>
        //Creates a new file named demo.txt in the default document library.
        //</summary>
        //<returns>A Boolean value that indicates whether the new text file was successfully created.</returns>
        internal async Task<String> CreateNewTextFileAsync()
        {
            //bool isSuccess = false;
            String newID = string.Empty;
            var sharePointClient = await AuthenticationHelper.EnsureSharePointClientCreatedAsync("MyFiles");

            try
            {
                // First check whether demo.txt already exists. If it exists, delete it.
                // If it doesn't exist, swallow the error.
                IItem item = await sharePointClient.Files.GetByPathAsync("demo.txt");
                await item.DeleteAsync();
            }
            catch (ODataErrorException)
            {
                // fail silently because demo.txt doesn't exist.
            }
           
            try
            {
                
                // In this example, we'll create a simple text file and write the current timestamp into it. 
                string createdTime = "Created at " + DateTime.Now.ToLocalTime().ToString();
                byte[] bytes = Encoding.UTF8.GetBytes(createdTime);

                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    // File is called demo.txt. If it already exists, we'll get an exception. 
                    Microsoft.Office365.SharePoint.FileServices.File newFile = new Microsoft.Office365.SharePoint.FileServices.File
                    {
                        Name = "demo.txt"
                    };

                    // Create the empty file.
                    await sharePointClient.Files.AddItemAsync(newFile);
                    newID = newFile.Id;

                    // Upload the file contents.
                    await sharePointClient.Files.GetById(newFile.Id).ToFile().UploadAsync(stream);
                }
            }

            // ODataErrorException can be thrown when you try to create a file that already exists.
            catch (Microsoft.Data.OData.ODataErrorException ex)
            {
                //isSuccess = false;
            }

            return newID;
        }
コード例 #7
0
ファイル: MyFilesHelper.cs プロジェクト: CherifSy/PnP
        public async Task UploadFile(string filePath, string folderId)
        {
            var client = await this.AuthenticationHelper
                .EnsureSharePointClientCreatedAsync(
                Office365Capabilities.MyFiles.ToString());

            client.Context.IgnoreMissingProperties = true;

            string filename = System.IO.Path.GetFileName(filePath);
            using (FileStream fileStream = System.IO.File.OpenRead(filePath))
            {
                SPOFileServices.File file = new SPOFileServices.File() { Name = filename };
                if (!String.IsNullOrEmpty(folderId))
                {
                    await client.Files.GetById(folderId).ToFolder().Children.AddItemAsync(file);
                }
                else
                {
                    await client.Files.AddItemAsync(file);
                }
                await client.Files.GetById(file.Id).ToFile().UploadAsync(fileStream);
            }
        }
コード例 #8
0
ファイル: SharePointTests.cs プロジェクト: iambmelt/Vipr
        public async Task AddFile()
        {

            var name = Guid.NewGuid().ToString() + ".jpg";

            var file = new File {Name = name};

            await file.UpdateAsync();

            await file.UploadAsync(Resources.ProfilePhoto);

            Assert.IsNotNull(file.Id, "Creation Failed");
        }
コード例 #9
0
    public async Task<IEnumerable<IItem>> GetMyFiles(int pageIndex, int pageSize) {
      // ensure connection established to new onedrive API
      if ((string.IsNullOrEmpty(_oneDriveAccessToken)) ||
          (string.IsNullOrEmpty(_oneDriveEndpoint)) ||
          (string.IsNullOrEmpty(_oneDriveResourceId))) {
        await InitOneDriveNewRestConnection();
      }

      // set the access token on the request
      _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _oneDriveAccessToken);

      // create the query for all file at the root
      var query = _oneDriveEndpoint + "/drive/root/children";

      // create request for items
      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, query);

      // issue request & get response
      var response = await _client.SendAsync(request);
      string responseString = await response.Content.ReadAsStringAsync();
      // convert them to JSON
      var jsonResponse = JsonConvert.DeserializeObject<JsonHelpers.FolderContents>(responseString);

      // convert to model object
      var items = new List<IItem>();

      foreach (var folderItem in jsonResponse.FolderItems) {
        // if folder
        if (folderItem.FileSize == 0) {
          var folder = new Folder {
            Id = folderItem.Id,
            Name = folderItem.Name,
            ETag = folderItem.eTag,
            DateTimeCreated = folderItem.CreatedDateTime,
            DateTimeLastModified = folderItem.LastModifiedDateTime,
            WebUrl = folderItem.WebUrl,
            Size = 0
          };
          items.Add(folder);
        } else {
          var file = new File {
            Id = folderItem.Id,
            Name = folderItem.Name,
            ETag = folderItem.eTag,
            DateTimeCreated = folderItem.CreatedDateTime,
            DateTimeLastModified = folderItem.LastModifiedDateTime,
            WebUrl = folderItem.WebUrl,
            Size = folderItem.FileSize
          };
          items.Add(file);
        }
      }

      return items.OrderBy(item => item.Name).ToList();
    }