views:

921

answers:

3

Hi everyone!

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.

Googling around, I've found some snippets, but in all of them I have to use the txt file path.

But, how can I get this path? This file could be anywhere in a user's machine!

Thanks!!

+1  A: 

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.

Ryan Christensen
Hi Ryan! I don't really need to save the txt file. I just need to read its content and save it to database
AndreMiranda
+3  A: 

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
    }
}
Jacob
Jacob, thanks! I was already going on this direction! :-) It is saving to database, but now I have problems with special characters such as "´", "~' and others.
AndreMiranda
I forgot to use the Encoding!! Thanks for everything!
AndreMiranda
A: 
var hpf = Request.Files[file] as HttpPostedFile;

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

Rony