Uploading a File Through An Asp.Net Web Service

by Bar Zohan 6. April 2010 00:48

Create a new asp.net web service or put this function into an existing one.

        [WebMethod]
        public string UploadFile(byte[] f, string fileName)
        {
            try
            {
                MemoryStream ms = new MemoryStream(f);
                FileStream fs = new FileStream(Server.MapPath("~/Files/") + fileName, FileMode.Create);
                ms.WriteTo(fs);

                ms.Close();

                fs.Close();

                fs.Dispose();

                return "OK";
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

Here our UploadFile function takes the file as a byte array in it's first parameter and writes it to a location on harddrive. In order to use this function you should read a file, convert it to byte array and pass the array as the first parameter of the function and name of the file as the second parameter of it. Here is another snippet for reading a file and converting o a byte array;

        private byte[] ConvertToStream(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            byte[] fData = new byte[fs.Length];
            fs.Read(fData, 0, System.Convert.ToInt32(fs.Length));
            fs.Close();

            return fData;
        }

Tags: , ,

.Net Framework | C# | Web | Asp.Net | MVC

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Page List