2012-07-04 142 views
1

我想實現一個簡單的文件上傳,但有一些麻煩。當我硬編碼的路徑工作正常。但由於某些原因,當我嘗試使用文件上傳,控制器名稱被附加到路徑文件上傳中的路徑問題?

硬編碼路徑(就是我試圖讓):

@"C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\LOADME.txt" 

路徑我掌握異常(注意 「appz」 控制器的名稱):

C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\appz\LOADME.txt' 

我的控制器

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 

     } 

我的看法

<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> 

什麼可能導致此行爲?

回答

0

試試這個:

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)回報文件的名稱

編輯

變化System.IO.Path.GetFileName(file.FileName)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, "#!#"); 
     } 
    } 
} 

編輯II

或複製到diferent路徑:

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, "#!#"); 
      } 
     } 
    } 
} 
+0

嘗試,和它現在給人一種完全不同的路徑 - 「無法找到文件'C:\ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0 \ LOADME1.txt'。」 – loveforfire33

1

您可以保存自己的物流的努力:

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);