0

I'm uploading to sharepoint using a c# client, and every file I Upload gets extra data included. A one line CSV file gets turned into a 7 line file that isn't usable. This is what my one line file upload turned into:

-----------AEE7A299-297A-41E0-B1CC-A72050FCDD28 
Content-Disposition: form-data; name="ControlFile_RCTI_statement_20220218_145832.csv"; filename="ControlFile_RCTI_statement_20220218_145832.csv"    
Content-Type: application/octet-stream  

File;Class;Account Number;Effective Date;Product;Account Type;Document Name 

-----------AEE7A299-297A-41E0-B1CC-A72050FCDD28--   

My upload code is using restSharp

public async Task UploadFile(string filePath, string list, string folderPath)
{
    await CheckTokenAsync();
    var fileName = Path.GetFileName(filePath);
    var endpoint = $"{spCredentials.sharepointSubSiteFullUrl}/_api/web/GetFolderByServerRelativeUrl('{list}/{folderPath}')/Files/Add(url='{fileName}', overwrite=false)";
    var client = new RestClient(endpoint);
    client.Timeout = 30000;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", $"Bearer {token}");
    request.AddHeader("Accept", "application/json;odata=verbose");
    request.AddFile(fileName, filePath);
    var response = await client.ExecuteAsync(request);
    if (response.StatusCode == HttpStatusCode.OK)
    {
        var fileData = JsonConvert.DeserializeObject<SPSingleResultContainer>(response.Content);
        var link = fileData.d.__metadata.uri;
        await SendRequest<string>($"{link}/CheckIn()", Method.POST);
    }
    else
        throw new Exception($"Upload Failed with message: " + response.ErrorMessage);
}

I've also uploaded this question to SO at https://stackoverflow.com/questions/71168414/uploading-files-to-sharepoint-with-restsharp-and-their-rest-api-is-adding-header

1 Answer 1

1

Helping anyone looking for the answer.

Replace request.AddFile(fileName, filePath); with

request.AddHeader("Content-Type", "application/octet-stream");
var fileData = System.IO.ReadAllBytes("C:\this-is-the-file-path.xlsx");
request.AddParameter("application/octet-stream", fileData, ParameterType.RequestBody);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.