简体   繁体   中英

Appending data to a text file within asp.net mvc project structure/tree (how to address the file?)

I am working on a simple landing page for a project that is sheduled to release in a couple of months. People can use a form to sign up to be notified on release. Currently the form simply generates an email saying "email adresse foo@bar.com wants to be notified on release" and sends it to me.

Now I want to save the data from the form into a simple text file so I can more easily feed it to my email programm later. In Visual Studio I created a new folder in my project named "subscriptions" and in that folder created an emptry text file release_notification_emails.txt". I tried using the StreamWriter to write to the file, but it failed. Here is my code:

using (StreamWriter writer = new StreamWriter("/subscriptions/release_notification_emails.txt", true))
        {
            writer.WriteLine(eMail);
        }

It results in the following exception/error

Could not find a part of the path 'C:\subscriptions\release_notification_emails.txt'.

So it looks like it treats the path parameter of the StreamWriter as relative to the file system root instead of the project root, which is problematic. I use paths relative to the project root all the time to include images, scripts, views, etc. It seemed to me that this was the standard way asp.net does this (I AM very new to asp.net though, you can probably tell).

So my question ow is: How can I write to a text file that is within my project/solution file tree? It doesn't have to use the StreamWriter I just want it to work. It needs to be within the project file tree so that it will be tracked by out version management system and colleagues working on the project have the same file.

您需要添加Server.MapPath以获取物理路径。

new StreamWriter(Server.MapPath("/subscriptions/release_notification_emails.txt"), true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM