2009-06-20 112 views
0

在我的ASP.NET MVC網站中,我必須閱讀一個txt文件,其中包含一些姓名和電子郵件,由';'分隔。之後,我必須將此txt文件的每一行保存到數據庫中。如何在C#3.0中獲取上傳的文件完整路徑?

谷歌搜索,我發現了一些片段,但在所有他們我必須使用txt文件路徑。

但是,我怎麼能得到這條路?這個文件可以在用戶機器的任何地方!

謝謝!

+0

這是一個ASP.NET網站? – heavyd 2009-06-20 02:39:01

+0

ASP.NET MVC,heavyd。 – AndreMiranda 2009-06-20 02:42:36

+0

@Jacob - 用戶將選擇一個txt文件,當他點擊某個按鈕時,將會調用一個Action。在此操作中,我必須讀取此txt文件的所有數據並將它們保存到數據庫。 – AndreMiranda 2009-06-20 02:47:05

回答

4

您無法獲取上傳文件的完整路徑。這將是上傳文件的用戶的隱私違規行爲。

相反,您需要閱讀已上傳的Request.Files。例如:

HttpPostedFile file = Request.Files[0]; 
using (StreamReader reader = new StreamReader(file.InputStream)) 
{ 
    while ((string line = reader.ReadLine()) != null) 
    { 
     string[] addresses = line.Split(';'); 
     // Do stuff with the addresses 
    } 
} 
1

如果你在一個asp.net網頁模型,然後Server.MapPath("~/")工程得到的網站的根,所以通過你需要的路徑。您可能需要調用

HttpContext.Current.Server.MapPath("~/"); 

例如在文本文件被保存在一個文件夾:

string directoryOfTexts = HttpContext.Current.Server.MapPath("~/txtdata/"); 

要只是從它讀一旦你擁有了它,你可以的StreamReader它:

string directoryOfTexts = HttpContext.Current.Server.MapPath("~/txtdata/"); 
string path = directoryOfTexts + "myfile.txt"; 
string alltextinfile = ""; 
if (File.Exists(path)) 
{ 
    using (StreamReader sr = new StreamReader(path)) 
    { 
     //This allows you to do one Read operation. 
     alltextinfile = sr.ReadToEnd()); 
    } 
} 

如果這是桌面應用程序,則Applcation類具有所有此信息:

http://msdn.microsoft.com/en-us/library/system.windows.forms.application.startuppath.aspx

Application.StartupPath 

所有屬性列出其他應用程序數據文件夾和東西,但一旦你的應用程序可執行文件的路徑這給你背景下,如Application.LocalUserAppDataPath

http://msdn.microsoft.com/en-us/library/system.windows.forms.application_properties.aspx

如果內容足夠小,你也可以只將它們保存在一個HashTable或通用List<String>保存到數據庫,以及前。

0
var hpf = Request.Files[file] as HttpPostedFile; 

在HTML表單應該有enctype="mulitipart/form-data"

相關問題