0

I try to upload a file to sharepoint using HttpWebRequest post method. But I get the error like the title show above. I have go through some similer questions but the solutions do not solve my problem.

You must write ContentLength bytes to the request stream before calling [Begin]GetResponse System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse

Here is my code.

public static string UploadFile(string filePath, string siteurl, string fileName, string formDigest, string token)
        {
            byte[] fileArray = File.ReadAllBytes(filePath);
            bool status = false;
            string result = string.Empty;
            //Url to upload file
            string resourceUrl = siteurl + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files/add(url='" + fileName + "',overwrite=true)";
            HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(resourceUrl);
            wreq.UseDefaultCredentials = false;
            //credential who has edit access on document library
            NetworkCredential credentials = new System.Net.NetworkCredential("username", "password", "domain");
            wreq.Credentials = credentials;

            //Get formdigest value from site

            wreq.Headers.Add("X-RequestDigest", formDigest);
            wreq.Headers.Add("Authorization", token);
            wreq.Method = WebRequestMethods.Http.Post;
            wreq.ContentType = "application/x-www-form-urlencoded";
            wreq.Timeout = 1000000; //timeout should be large in order to upload file which are of large size
            wreq.Accept = "application/json; odata=verbose";
            wreq.ContentLength = fileArray.Length;
            try
            {
                using (System.IO.Stream requestStream = wreq.GetRequestStream())
                {
                    requestStream.Write(fileArray, 0, fileArray.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
                using (StreamReader reader = new StreamReader(wresp.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    status = true;
                    return result;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
                throw;
            }
        }

0 Answers0