Search code examples
c#dotnetzip

Writing and Loading files that are in the C# Project?


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!


Solution

  • 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?.