简体   繁体   中英

Txt project file writing problems C#

I don't understand why I can read but cannot write to the file that is inside the project. When i selected release it appeared to write to the file, but on debugging mode it doesn't. When i use same function to write list into the file's lines to a different folder it worked always but not on the file that i want.

Example: Function:

public void WriteLinesFromListToTextFile(List<string> listOfContent, string txtFileName)
{
    StreamWriter writer = File.AppendText(txtFileName);
    foreach (string Item in listOfContent)
    {
        writer.WriteLine(Item);
    }
    writer.Flush();
    writer.Close();
}

and later

List<string> exampleList = new List<string>();
tmp.Add("line1");
tmp.Add("line2");
tmp.Add("line3");
WriteLinesFromListToTextFile(exampleList, "TextOnProjectRoot.txt")

In the file properties I selected "Copy Always" and also tried "Copy If Newer". I ran VS as admin as well. When I created the file it did copy it to the root folder but just didn't write to it. I also want to state that there is no exception at all. Thanks for any help

I'm a little unsure of what you are trying to archive, but I understand you this way:

You have a text file as part of you project. At runtime, you try to write some text to this file. When you application is closed, you expect to see the changes in the text file that's part of your project.

Am I right?

If so, I would guess the problem is as follow: When you first start your application, the text file that is part of your project is copied to the output folder together with your executable. The program runs, and the file is manipulated. But when the application closes, files are never copied back from the output folder to the project folder. That's just not how thing works...

If your program needs access to a file, and you don't specify a path, it uses the current location of the .exe. If this is good enough for your purposes then you just need to know that you can't add it to the solution; like Vegar said, it doesn't work that way. What you CAN do is compile your program, then browse to the folder where the .exe is (debug, release, or other) and run the .exe right from there, then open the text file and review your changes. If you need to create or ensure the file already exists, you can do that in the code as well. You won't be able to include it in your solution but you can still write to the file.

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