Revision: 31007
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at August 27, 2010 05:37 by myke
Initial Code
public String Upload()
{
var fileName = Path.GetFileNameWithoutExtension(Request.Files[0].FileName);
string extension = System.IO.Path.GetExtension(Request.Files[0].FileName);
if (Request.Files.Count > 0 && extension == ".pdf")
{
Request.Files[0].SaveAs(Server.MapPath("/Content/userfiles/wholesale/") + FilenameFromTitle(fileName, extension));
return "1";
}
else
{
return "0";
}
}
public static string FilenameFromTitle(string name, string extension)
{
DateTime time = DateTime.Now;
string format = "MMddyy_HHmmss";
//Console.WriteLine(time.ToString(format));
// first trim the raw string
string safe = name.Trim();
// replace spaces with hyphens
safe = safe.Replace(" ", "-").ToLower();
// replace any 'double spaces' with singles
if(safe.IndexOf("--") > -1)
while(safe.IndexOf("--") > -1)
safe = safe.Replace("--", "-");
// trim out illegal characters
safe = Regex.Replace(safe, "[^a-z0-9\\-]", "");
// trim the length
if(safe.Length > 50)
safe = safe.Substring(0, 49);
// clean the beginning and end of the filename
char[] replace = {'-','.'};
safe = safe.TrimStart(replace);
safe = safe.TrimEnd(replace);
safe = safe.ToLower() + "_" + time.ToString(format) + extension;
//safe = safe.ToLower() + extension;
return safe;
}
Initial URL
Initial Description
Initial Title
C# File upload with safe filename
Initial Tags
Initial Language
C#