Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 25064

Remote Server Returned 401 Error when Downloading a file from SharePoint Programatically

$
0
0

Hi..

While downloading a file from Sharepoint Server i am getting "The Remote Server returned an error: (401) authorized Error"

I am getting while downloading from Client machine and that too only for Excel file.

Sending the Code for Downloading..Need anything to update

 //Download File
        protected void lnkDownload_Click(Object sender, CommandEventArgs e)
        {
            try
            {
                if (e.CommandArgument != null)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite oSPsite = new SPSite(SPContext.Current.Site.Url.ToString()))
                        {
                            string str = SPContext.Current.Site.Url;
                            using (SPWeb oSPWeb = oSPsite.OpenWeb())
                            {
                                oSPWeb.AllowUnsafeUpdates = true;
                                SPList list = oSPWeb.Lists["AMS_Management_PermanentFiles"];
                                SPQuery query = new SPQuery();
                                query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + e.CommandArgument + "</Value></Eq></Where>";
                                SPListItemCollection colitem = list.GetItems(query);
                                DataTable dt = new DataTable();
                                dt = colitem.GetDataTable();

                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    string url = @"" + str + "/AMS_Management_PermanentFiles/" + dt.Rows[0]["FileLeafRef"];
                                    WebClient client = new WebClient();
                                    client.UseDefaultCredentials = true;
                                    client.DownloadFile(new Uri(url), @"C:\Windows\Temp\" + dt.Rows[0]["FileLeafRef"]);

                                    //added Code
                                    string fileName = Convert.ToString(dt.Rows[0]["FileLeafRef"]);
                                    // get the file bytes to download to the browser
                                    byte[] fileBytes = System.IO.File.ReadAllBytes("C:\\Windows\\Temp\\" + fileName);
                                    // NOTE: You could also read the file bytes from a database as well.

                                    // download this file to the browser
                                    StreamFileToBrowser(fileName, fileBytes);



                                }
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        // Streaming File to Browser
        public void StreamFileToBrowser(string sFileName, byte[] fileBytes)
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
            context.Response.ContentType = GetMimeTypeByFileName(sFileName);
            context.Response.AppendHeader("content-disposition", "attachment; filename=" + sFileName);
            context.Response.BinaryWrite(fileBytes);

            context.Response.Flush();
            context.Response.End();

            context.ApplicationInstance.CompleteRequest();
        }

        // Get Type of File Name
        public string GetMimeTypeByFileName(string sFileName)
        {
            string sMime = "application/octet-stream";

            string sExtension = System.IO.Path.GetExtension(sFileName);
            if (!string.IsNullOrEmpty(sExtension))
            {
                sExtension = sExtension.Replace(".", "");
                sExtension = sExtension.ToLower();

                if (sExtension == "xls" || sExtension == "xlsx")
                {
                    sMime = "application/ms-excel";
                }
                else if (sExtension == "doc" || sExtension == "docx")
                {
                    sMime = "application/msword";
                }
                else if (sExtension == "ppt" || sExtension == "pptx")
                {
                    sMime = "application/ms-powerpoint";
                }
                else if (sExtension == "rtf")
                {
                    sMime = "application/rtf";
                }
                else if (sExtension == "zip")
                {
                    sMime = "application/zip";
                }
                else if (sExtension == "mp3")
                {
                    sMime = "audio/mpeg";
                }
                else if (sExtension == "bmp")
                {
                    sMime = "image/bmp";
                }
                else if (sExtension == "gif")
                {
                    sMime = "image/gif";
                }
                else if (sExtension == "jpg" || sExtension == "jpeg")
                {
                    sMime = "image/jpeg";
                }
                else if (sExtension == "png")
                {
                    sMime = "image/png";
                }
                else if (sExtension == "tiff" || sExtension == "tif")
                {
                    sMime = "image/tiff";
                }
                else if (sExtension == "txt")
                {
                    sMime = "text/plain";
                }
            }

            return sMime;
        }


Ravindranath


Viewing all articles
Browse latest Browse all 25064

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>