Skip to content

Instantly share code, notes, and snippets.

@mraarif
Last active February 25, 2018 19:05
Show Gist options
  • Save mraarif/fd7c13687eb8d95bba47ea408b098954 to your computer and use it in GitHub Desktop.
Save mraarif/fd7c13687eb8d95bba47ea408b098954 to your computer and use it in GitHub Desktop.
C# How to automatically rename uploaded file if there's already a file with same name
using System.IO;
using System.Linq;
using System.Web;
namespace static class FileUploadHelper
{
//customize the file size limit accordingly
private const double MaximumFileSize=10*1024*1024;
public static string UploadFile(HttpPostedFile file)
{
if(file.ContentLength <=0 && file.ContentLength > MaximumFileSize)
thorw new Exception("Error uploading the file");
//your uploads directory path
var uploadsDirectoryPath="Uploads";
var absolutePath = HttpContext.Current.Server.MapPath($"~/{uploadsDirectoryPath}");
if (!Directory.Exists(directoryAbsolutePath))
Directory.CreateDirectory(directoryAbsolutePath);
var suggestedFileName = GetSuggestedFileName(directoryAbsolutePath, file);
SaveFile(suggestedFileName, directoryAbsolutePath, file);
//returning the file's relative path (updated path in case file name was updated)
return Path.Combine(uploadsDirectoryPath, suggestedFileName);
}
private static string GetSuggestedFileName(string filesDirectory, HttpPostedFile file)
{
var extension = Path.GetExtension(file.FileName);
var uploadedFileName = Path.GetFileNameWithoutExtension(file.FileName);
var count = Directory.GetFiles(filesDirectory).Select(Path.GetFileNameWithoutExtension)
.Count(x => x.StartsWith(uploadedFileName));
return count > 0 ? $"{uploadedFileName}_{count+1}{extension}" : $"{uploadedFileName}{extension}";
}
private static void SaveFile(string fileName, string directoryToSave, HttpPostedFile file)
{
var pathToSave = Path.Combine(directoryToSave, fileName);
file.SaveAs(pathToSave);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment