How can I get uploaded file full path in C# 3.0?

前端 未结 3 1708
名媛妹妹
名媛妹妹 2020-12-22 07:56

In my ASP.NET MVC website, I have to read a txt file with some names and emails separeted by \';\'. After that, I have to save each line of this txt file to database.

<
相关标签:
3条回答
  • 2020-12-22 08:11
    var hpf = Request.Files[file] as HttpPostedFile; 
    

    the form in the HTML should have enctype="mulitipart/form-data"

    0 讨论(0)
  • 2020-12-22 08:13

    You cannot get the full path of an uploaded file. This would be a privacy violation for the user that uploaded the file.

    Instead, you'll need to read the Request.Files that have been uploaded. For example:

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-22 08:18

    If you are on a asp.net web page model then Server.MapPath("~/") works to get the root of the site so pass the path you need. You might need to call

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

    For instance a folder where the text files are saved:

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

    To just read from it once you have it you can StreamReader it:

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

    If this is for a desktop application then the Applcation class has all this information:

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

    Application.StartupPath
    

    All properties list other appdata folders and stuff but once you have the application path to the executable this gives you context such as Application.LocalUserAppDataPath.

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

    If the content is small enough you could also just save them in a HashTable or a Generic List<String> before saving to the database as well.

    0 讨论(0)
提交回复
热议问题