Last active
February 25, 2018 19:05
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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