Reputation: 1110
I am trying to implement a simple file upload, but having some troubles. When I hard-code the path it works fine. But for some reason, when I try to use a file upload, the controller name is being appended to the path
Hard coded path (what I'm trying to get):
@"C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\LOADME.txt"
Path I am getting an exception with (notice the "appz" controller name):
C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\appz\LOADME.txt'
My Controller
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
string filePath = Request.MapPath(file.FileName);
string input = System.IO.File.ReadAllText(filePath);
string[] lines = Regex.Split(input, "#!#");
// ...... do stuff
}
My View
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="LOAD ME!">
</form>
What could be causing this behavior ?
Upvotes: 1
Views: 3816
Reputation: 65426
You can save yourself the effort of the streams:
string filename = Request.Files["file"].FileName;
string filePath = Path.Combine(Server.MapPath("~/YourUploadDirectory"), filename);
HttpPostedFileBase postedFile = Request.Files["file"] as HttpPostedFileBase;
postedFile.SaveAs(filePath);
string input = File.ReadAllText(filePath);
Upvotes: 1
Reputation: 14967
try this:
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
if (file.ContentLength > 0)
{
var filePath = System.IO.Path.GetFileName(file.FileName);
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
{
var input = sr.ReadToEnd();
var lines = Regex.Split(input, "#!#");
}
}
}
(bug) System.IO.Path.GetFileName(file.FileName)
return the name of file
Edit
change System.IO.Path.GetFileName(file.FileName)
for Server.MapPath(file.FileName)
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
if (file.ContentLength > 0)
{
var filePath = Server.MapPath(file.FileName);
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
{
var input = sr.ReadToEnd();
var lines = Regex.Split(input, "#!#");
}
}
}
Edit II
or copy to diferent path:
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
if (file.ContentLength > 0)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var fileUpload = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(fileUpload);
if (System.IO.File.Exists(fileUpload))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileUpload))
{
var input = sr.ReadToEnd();
var lines = Regex.Split(input, "#!#");
}
}
}
}
Upvotes: 0