0

在我的 ASP.NET MVC 网站中,我必须阅读一个 txt 文件,其中包含一些由“;”分隔的名称和电子邮件。之后,我必须将此 txt 文件的每一行保存到数据库中。

谷歌搜索,我找到了一些片段,但在所有片段中我都必须使用 txt 文件路径。

但是,我怎样才能得到这条路?这个文件可以在用户机器的任何地方!

谢谢!!

4

3 回答 3

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
    }
}
于 2009-06-20T02:54:07.493 回答
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

所有属性都列出了其他 appdata 文件夹和内容,但是一旦您获得了可执行文件的应用程序路径,这将为您提供上下文,例如Application.LocalUserAppDataPath.

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

如果内容足够小,您也可以在保存到数据库之前将它们保存在 aHashTable或 Generic中。List<String>

于 2009-06-20T02:41:41.027 回答
0
var hpf = Request.Files[file] as HttpPostedFile; 

HTML 中的表单应该有enctype="mulitipart/form-data"

于 2009-06-20T04:22:21.903 回答