Frage

After much searching and looking extensively, I have a question that is undoubtedly dumb but I'm just missing something easy. I just published my first website and obviously had to make a few changes. I'm using a writer class, before it was just writing to a path on my computer, but that's obviously not an option now, what I'm trying is this:

using (StreamWriter writer = new StreamWriter(@"~\Files\test.txt"))

I just want this to write this to the Files folder in my project. What's the syntax? I'm also using dotnetzip and having the same issue trying a different syntax:

zip.AddFile("Files/test.txt");

What's the way to do this? Thanks!

War es hilfreich?

Lösung

For a Windows (desktop) application, do:

Path.Combine(Application.StartupPath, "Files", "test.txt")

The application path is accessible in Application.StartupPath, and you can use Path.Combine to combine parts of a path together.

For ASP.net, you need Server.MapPath instead of Application.StartupPath:

Path.Combine(Server.MapPath("~", "Files", "test.txt")

Of course since this is all hardcoded, you should also be able to simply do

Server.MapPath("~/Files/test.txt")

Depending on your needs, you may need to use . instead of ~. See also Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?.

Andere Tipps

Awesome thanks to Ic. for the response. I neglected to mention this is a asp.net project but I figured out that the equivalent in asp.net is:

Server.MapPath(".")

There are numerous options instead of the . but that's what I'm looking for. Also, I was trying to set this up in a class and that wasn't working, because I needed to do this:

HttpContext.Current.Server.MapPath(".")

Thanks!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top