Reputation: 73
so in the project a user could upload, download, delete, preview and search for (in real time) a file. The files are stored in a folder called "Uploads" inside of the wwwroot folder. As of now, the code has absolute pathing, but the project will need to be on different computers so I need relative pathing, can anyone help me out with a sample syntax?
[HttpPost]
public async Task<IActionResult> Index(IFormFile fifile, string category)
{
string path = @"C:\Users\panara5\source\repos\Proiect2PracticaClona\Proiect2PracticaClona\wwwroot\Uploads\";
var fisave = Path.Combine(path, fifile.FileName);
var stream = new FileStream(fisave, FileMode.Create);
await fifile.CopyToAsync(stream);
Files fileModel=new Files()
{
info = fifile.FileName,
category = category
};
_fileRepository.AddFile(fileModel);
stream.Close();
files = _fileRepository.GetFileList();
return RedirectToAction("Index",files);
}
public IActionResult Index(string id)
{
files = _fileRepository.GetFileList();
if (id == null)
return View(files);
List<Files> sortedfiles = new List<Files>();
foreach (var item in files)
{
if (item.category == id)
{
sortedfiles.Add(item);
}
}
return View(sortedfiles);
}
public IActionResult Delete(string filedel)
{
filedel = Path.Combine("~/Uploads/", filedel);
FileInfo fi = new FileInfo(filedel);
if (fi != null)
{
System.IO.File.Delete(filedel);
fi.Delete();
}
return RedirectToAction("Index");
}
also i get a null reference when trying to delete
Upvotes: 0
Views: 920
Reputation: 8245
I believe you want IWebHostEnvironment.WebRootPath
You need to use Dependency Injection to get access to it, but after that, you can just reference and Path.Combine. See below:
public class FileController : Controller
{
private readonly IWebHostEnvironment environment;
public FileController(IWebHostEnvironment env)
{
this.environment = env;
}
private string UploadFilePath() => Path.Combine(environment.WebRootPath, "uploads");
}
Upvotes: 1