Txt project file writing problems C# - 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.

Related

Export WindowsForm with images and files

Well, I don't if I asked well this question because I have the next problem:
Code
As you can see here, in one of my many WindowsForms I read a specific file.exe as well with file.txt with their own directions, when I run this (Debug) it works perfectly fine because the Folder that storage those files are inside of \WindowsFormsApp1\WindowsFormsApp1\bin\Debug.
Maybe the worst idea, because I want to 'release' this project, once I do this, I get a lot of errors of missing files (Because of the folder) except with certain images that I imported to Resources.rex.
Any suggestion?, like how can I keep all those .txt files with the .exe files, and still reading and running them when I use 'release' from Visual Studio
EDIT:
Error
This is the Release version, some images are intact but when I try to read the .txt files or Run the .exe files I get this message
If you have created exe for that, best suggestion that store those files in C drive as there will be no such folder of debug or release when you export exe. And even instance will be running from another folder which may be not same as you have provided folder path in your application. You should provide a path of folder, if that path is not present then create the folder as below.
string folderPath = "C:\\YourFolderPath\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
This may solve the issue but it is not still correct way to do.

how to access/create a .txt file with a "relative" path

I'm creating an app that can take a text from one file, read it, edit the text via a string, then write the edited string in a new text file.
My problem is that the file can't be found. In the following example I placed the file in the folder indicated in the screenshot and in another attempt in the 'bin' file, both without success and identical error message.
What I was trying to a achieve is the the following (as I am aware I could write the whole path from "C:\"), the text file should be somewhere in the application's directory so that the whole app can be moved without having to re-write the path.
So I need a way to write a "relative" path, if such thing is possible. this should pls work with creating a file similarly as well.
screenshot of the error message
visual studio screenshot with code and file location
thanks in advance.
Summary / Explanation: The file is not found because the directory you have set is not the directory of the file. If the file is in the same directory as to the C# file you are currently working on, then there's no need to add a folder's directory into it but rather just type the filename. You can also consider what's written below this paragraph.
FIRST:
Click InputText.txt
SECOND:
Right Click and Choose "Properties" or just press Alt + Enter
THIRD:
Set the "Build Action" property to "Embedded Resource"
FOURTH:
Set the "Copy to Output Directory" property to "Copy always"
LASTLY:
Change the Readline's first parameter to -> #"InputText.txt"
...
foreach (string line in File.ReadLines(#"InputText.txt", Encoding.UTF8))
{
originalTextInLines.Add(line);
}
...
This is the sample output (in my case of trying this).
This is the file that the example application above
The file is in the same directory the Program.cs is found that the file may be addressed by typing its filename only.

WPF How to modify resource/content file inside my project folder at runtime (NOT in bin directory)? Implementing "Recent changes" section

I would like to modify the contents of a file placed in my project folder (Specifically "Assets/recentChanges.txt") at runtime. Let's say it contains information about recent changes in application. It is supposed to be read and bound to a textbox control, which later on can be edited by developers and saved back. The problem with content files is that they are copied to output directories and therefore I'm not editing the original file in Assets folder, but the one in bin/Debug/Assets/ folder. And the Embedded Resource build action is not an option since such files cannot be modified.
The question is: how can I modify mentioned .txt file in its original root/Assets/recentChanges.txt location during runtime? All of the below instructions point to similiar build-dependant path:
Environment.CurrentDirectory;
Assembly.GetExecutingAssembly().Location;
Or, in other words, what would be the correct approach for implementing "Recent Changes" section with following conditions:
based on text file in its original project location
possibilty to modify the file at runtime through UI
file copied to the output folder and visible to the user (through textbox) in published application
I am aware that it's probably not the perfect approach, because "recent changes" info could be collected from database or the .txt file could be modified manually and then copied to output locations... but nevertheless I think the issue is somewhat confusing and I would love some help. Thanks!
The compiled and running application doesn't know anything about some "original" location. This location is only important to Visual Studio when the application is built.
If you want to modify the file in this folder you should specify an absolute path to it, i.e. "c:\your_project_folder\file.txt".
The .exe cannot be supposed to know from where it was compiled

FileNotFound Exception While Opening File

I have a project that reads several text files into a List via StreamReader, I have the files added to my solution under Resources, when I try to reference the file using StreamReader, I get a "FileNotFound" exception.
The files are being copied over to bin\debug\Resources, and the error says it's trying to locate them under bin\debug.. How do I reference them without using the literal path? (e.g. C:\users\etc) since when I compile it won't run on another person's PC if I reference actual path.
Code that calls text file:
using (sr = new StreamReader("FileName.txt"))
{
while (!sr.EndOfStream)
Names.Add(sr.ReadLine());
}
Under the text files properties I have it set to "Copy Always" and under Build Action it's set to "Embedded Resource".
Basically my main goal is to compile the project into an exe with the text files being referenced internally (their contents aren't changed by the program), so my application will be portable.
Error is clear. Change code to:
using (sr = new StreamReader("Resources\FileName.txt"))
{
while (!sr.EndOfStream)
Names.Add(sr.ReadLine());
}
In your situation, the error will be removed by just replacing the path Resources\FileName.txt
In other case, as you mentioned that you want to make a portable .exe. Then you need to embed files in your application. Now see how to embed files in your .exe :
Expand Properties in Solution Explorer
Double click on Resources
On left top of Resources tab, there will be a combo box
Choose Files
Now just drag and drop your files there
To embed files, you can go to properties of every file by right
clicking on it. Choose Embedded in .resx from Persistence
property.
To use the file you can use Properties.Resources.YourFile.
For more details, follow the link http://msdn.microsoft.com/en-us/library/7k989cfy(v=vs.80).aspx

avoid hard coding path in ReadAllText

My exact file path is as follows. This .txt file is not supposed to be deployed to bin/debug
string str = File.ReadAllText(#"C:\development\slnfolder\projfolder\myfile.txt");
How can I write the code so that I do not have to hard code full path to get to the file
I am trying to avoid hard coding path in the above line of code as follows:
string file = #"myfile.txt";
string str = Path.GetFullPath(file);
but the str ends up being as follows and is not able to find the file.
C:\development\slnfolder\projfolder\bin\debug\myfile.txt
You can include myfile.txt in your Visual Studio solution and go to its properties and set the Build action to Copy always (or Copy if newer if you want to avoid copying the file if it didn't change since the previous build...).
This way you're going to have the whole file in the target directory (i.e. bin\debug).
That's where it should map, because that's where your executable is running from. I'd highly suggest you ensure that the text file is moved to the bin/debug folder (there's a VS option to copy it down in properties) rather than trying to read two levels up. It will be much easier once you end up deploying your app instead of running it from visual studio.
If you're using Visual studio, than add the txt file to your project
right click on properties
set build action to none
and set copy to output directory to copy if newer
this will ensure that the txt file is always in the same folder as your executable
To avoid hard-coding something, you should:
"Soft-code" it (i.e. make it part of your product's configuration). You can use Configuration Settings APIs for that.
Take it as a parameter on the command line (read the directory location from one of the args passed to the Main method), or
Make a convention as to where it should be located, for example, in the data directory, which is a subdirectory of your current running directory (read from #"..\data\myfile.txt").
You can always define a combination of these methods, for example, use the "by convention" location when the configuration / command line option has not been specified.

Categories