using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.Services; namespace WebApplication1 { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class WebService1 : WebService { [WebMethod] public void HelloWorld() { string errorMessage = ""; string response = ""; string rootPath = "C:\\Temp\\"; string fileName = Context.Request.Files["media"].FileName; if (Context.Request.Files["media"].ContentLength > 1350000) errorMessage = "Your file is too large."; if (Context.Request.Files["media"].ContentType != "application/octet-stream") errorMessage = String.Format("Invalid file type, file type = {0}", Context.Request.Files["media"].ContentType); try { fileName = NextUniqueFilename(fileName, f => File.Exists(Path.Combine(rootPath, f))); } catch (Exception e) { errorMessage = e.Message; } if (errorMessage == "") { Stream sparkStream = Context.Request.Files["media"].InputStream; FileStream fileStream = File.Create(String.Format("C:\\Temp\\{0}", fileName)); sparkStream.CopyTo(fileStream); fileStream.Close(); } if (errorMessage == "") response = ""; else response = String.Format("", errorMessage); this.Context.Response.Write(response); } /// /// Finds the next unused unique (numbered) filename. /// /// Name of the file. /// Function that will determine if the name is already in use /// The original filename if it wasn't already used, or the filename with " (n)" /// added to the name if the original filename is already in use. private string NextUniqueFilename(string fileName, Func inUse) { if (!inUse(fileName)) { // this filename has not been seen before, return it unmodified return fileName; } // this filename is already in use, add " (n)" to the end var name = Path.GetFileNameWithoutExtension(fileName); var extension = Path.GetExtension(fileName); if (name == null) { throw new Exception("File name without extension returned null."); } const int max = 9999; for (var i = 1; i < max; i++) { var nextUniqueFilename = string.Format("{0} ({1}){2}", name, i, extension); if (!inUse(nextUniqueFilename)) { return nextUniqueFilename; } } throw new Exception(string.Format("Too many files by this name. Limit: {0}", max)); } } }