In one of my projects i store files just in folder and FilePath in database for linked entity(relation is 1-to-1).
I just created entity for File with byte[] property and domain service for saving files on server. In InsertFile i call filehandler that saves bytes on disk.
public IQueryable<WebFile> GetFiles()
{
string path = "~/Upload";
List<WebFile> webFiles = new List<WebFile>();
if (string.IsNullOrEmpty(path)) return webFiles.AsQueryable();
DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(path));
foreach (FileInfo file in di.GetFiles())
{
webFiles.Add(new WebFile { FileName = file.Name });
}
return webFiles.AsQueryable();
}
public void InsertFile(WebFile file)
{
FileHandler.HandleFile(file);
}
Link in database is just filename (because there is one folder, no reason to storing full path)
FileHandler code:
public class FileHandler
{
public static void HandleFile(WebFile file)
{
string uploadDir = "~/Upload";
if (!string.IsNullOrEmpty(uploadDir))
{
if (uploadDir.IndexOf("~/") == 0)
uploadDir = HttpContext.Current.Server.MapPath(uploadDir);
if (uploadDir.LastIndexOf("/") == uploadDir.Length - 1)
uploadDir = uploadDir.Substring(0, uploadDir.Length - 1);
string fullFileName = string.Format("{0}/{1}", uploadDir, file.FileName);
if (File.Exists(fullFileName))
{
string ext = fullFileName.Substring(fullFileName.LastIndexOf("."));
string fName = fullFileName.Substring(0, fullFileName.LastIndexOf("."));
fullFileName = string.Format("{0}_1{1}", fName, ext);
}
File.WriteAllBytes(fullFileName, file.FileContent);
}
}
}