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

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

但是,我怎么能得到这条路呢?该文件可以是用户机器中的任何位置!

谢谢!

有帮助吗?

解决方案

您无法获取上传文件的完整路径。这对于上传文件的用户来说是违反隐私的行为。

相反,您需要阅读已上传的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
    }
}

其他提示

如果您使用的是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 /库/ system.windows.forms.application.startuppath.aspx

Application.StartupPath

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

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

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top