FileNotFoundException when reading file using FileInfo - c#

I'm currently using fileinfo to use a xsd file in a xml validator.
I have 3 projects, a GUI, interface, project. A input project and a testproject.
Inside the input project i have a class that creates a FileInfo Object based on a path to a file that is also inside the same object:
new FileInfo(#"Xsd\Version_813\kvppt-8130.xsd")
This gives me trouble when i'm running my tests and my GUI. For example when i start my GUI, sometimes the code works and there is no problem but other times FileInfo will search the Bin/debug folder from the GUI project and the XSD isnt there.
I know that this is intended but is there a way to make this work for the unittest Project and the GUI project.
I have tried the following:
var executingFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
var path = executingFileInfo.DirectoryName + Path.DirectorySeparatorChar + #"Xsd\Version_813\kvppt-8130.xsd";
Return new FileInfo(path);
But this isn't the solution because it will still pick the startup project.
--- Edit:
After trying some of the suggestions in the comments i found out that my problem is a bit diffrent. I found out that if i press rebuild all before running my application, the files are always copied to their correct folder. It only fails if i just run the application.
Properties of the files are on "Copy always"

...sometimes the code works and there is no problem but other times
FileInfo will search the Bin/debug folder from the GUI project and the
XSD isnt there.
Make sure on the properties of the file (from within Visual Studio) you have "Copy to Output Directory" set to either "copy always" or "copy if newer"

Related

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.

Visual Studio 2010 Manage Output Files

I'm new about code developing with Visual Studio 2010 and I would like to ask you a simple question about something after build a project.
I have a C# project and when I build It in Release mode some file are created and some of them copied from another in to \output\bin\Release\ folder. My question is that How can I manage that which created dll or created file will be in \output\bin\Release\ folder.
I tried to take a look at build properties of project but I could not find any option about it.
Thank you.
Actually I do not need this dll in my project output folder because I
add this dlls as a reference to my project
And this is exactly why this file appear in output folder.
There are several ways to "put" file in output folder. For normal files in the project you can set property Copy to Output Directory.
If we talking about dll's, (as mentioned Hans), there is Copy Local property for each assembly in References.
By default VS set this according to our GAC, so if you are using 3rd part assembly or from another project VS will set this property to True and file will be copied to output folder.
If you don't want to put this file in output folder, just set this property to False. But remember, at run time this assembly should exist.
For more information: How to: Set the Copy Local Property of a Reference
Another explanation: you just messed up with Output path in the project properties and two project has the same output folder. :)
I suggest that you ignore the extra files that are created. One way to do this is to configure the destination of these to a different location.
I use this:
property pages->General
- Output Directory = $(SolutionDir)..\link\
- Intermediate Directory = c:\temp\vc10\$(SolutionName)\$(Configuration)\
Use the same settings for debug and release.

C# console app: reference file without ..\..\filename

I need to read data from a file in a c# console application.
What works: new StreamReader(#"..\\..\myData.csv");
Problem:
the ..\\..\ work because my exe file is in the bin/Debug directory
When I deploy my project the path doesn't work any longer
Question:
How can I reference myData.csv regardless of the location of the exe file?
I had hoped to find a method that returns the 'root' of my console application
So far I tried the following:
Process.GetCurrentProcess().MainModule.FileName
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location
Path.GetFullPath("bp.csv")
AppDomain.CurrentDomain.BaseDirectory
Directory.GetCurrentDirectory()
All of these expressions lead me to the directory of the exe file not the root.
I just started to read about isolated storage but it would be nice to have something simpler. Any suggestions / recommendations?
The simplest option is probably to add your CSV file to the solution and right-click it in VS and set the build action to "Copy if newer", which will output it together with the .exe (to the Debug or Release folder) when you build.
In the code, you can get the current location of the executing assembly like this:
string folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
And then you can combine the path with the CSV file name:
string filePath = Path.Combine(folder, "myData.csv");
Where your myData.csv will be stored ? You should have an absolute location of this file.
there are couple of options
You can place this file at the same directory where your exe is placed so you will only need to do
new StreamReader("myData.csv");
you can define file location in the App.Conig file and read that location.
you can set a path variable an read the PATH variable.
You should change your code to
new StreamReader("myData.csv");
This will ensure that the data is always read from the same folder the .exe is run from.
After that, you can create a post build step to copy the file to the deployment folder (or a subfolder) so that even in your debug environment the file will be in the correct place. The property "Copy to Output Folder" on the data file will do this as well if you just need the file to be in the output path for a project.
If you need more control, n the post build steps you can use macros like $(ProjectPath) to reference where the project files are located and $(TargetDir) to reference where the output directory will be.

Why does "Copy if newer" not copy a file when the file is updated?

I have a solution in Visual Studio Express that looks like this:
The LogicSchema class in C# that will parse a specified XML file at run-time. The following is in the main method of Program.cs:
LogicSchema ls = new LogicSchema(
XDocument.Load(
"schemas\\C#Schema.xml",
LoadOptions.PreserveWhitespace));
I created a folder in my solution called "schemas" to save the XML file and set the Build Action to Content and the "Copy to Output Directory" value to be Copy if newer.
My expectation is that if open the file in notepad, make a change, and save it, the updated version of the XML file will be copied to the ouput directory (in this case, bin\debug) when I press F5. However, the updated file is not copied to the output directory unless I select Rebuild. Regular Build does not work.
What do I need to change so that when I press F5, the file is copied to the output directory when it's been updated?
It seems to work also in Visual Studio 2008 Team System -
must be Expression edition specific, so cannot repro...
OK, my original guess was not true - it is about XML file being in the referenced library. Can repro it now.
I think the most natural way would be to embed the XML as resource and then read it with GetManifestResourceStream(). This way, the XML file would follow your dll as you reference it without copying it separately even if you reference the dll directly and not through project reference.
...or then you could use Pre-build event? (Project properties - Build Events):
copy $(ProjectDir)test.xml $(SolutiontDir)projectFolder\bin\debug\test.xml
I would think it will always run even if VS thinks no source files have changed. At least in full VS2008 this is the case - just tested.

C# File Location Connundrum

I have an xml file in a WCF application that describes dependencies. It is loaded when the service facade constructor runs and works great when testing the app alone. The way our separate web testing application is setup is an endpoint in a different (mvc) project - So the relative paths are different to the xml file that we need to load. The question is what would be the best way to load that file from both projects (so that when you run the first project alone it loads the file, but then when that dll is loaded in the second project it can still find the xml file)?
You could copy it to the output directory. You can do this from Visual Studio by right clicking the file, choosing properties and changing "Copy To Output Directory" to "Copy Always".
At runtime you will be able to find the file in the current directory in both projects.
Try Server.MapPath
example:
Server.MapPath (#"~\App_Data\menudata.xml")
then you can place your file in any location relative to the root directory of your website/webservice.
I tried the "Copy To Output" with no luck - for some reason my root path was not where the output path was (which i previously thought)... So to abstract away any headaches from other developers setting up this project I did this:
var _assembly = System.Reflection.Assembly.GetExecutingAssembly();
XDocument xdoc = XDocument.Load(new StreamReader(_assembly.GetManifestResourceStream("TheNamespace.Api.TheFile.xml")));
Which of course requires the file to be an embedded resource.

Categories