media media - 1 year ago 78
C# Question

How to use resources and files in C#

I have a program that consists of images. I want to put some images in a folder and show the content of that folder dynamically. the program should be portable. What should I do? I tried the following code but did not work:

String path = "Resources/Location.txt";
String path2 = "/IconImagesForDummies/Icon";
ObservableCollection<IconImagesForDummies> icons = new ObservableCollection<IconImagesForDummies>();
String[] lines = null;
if (File.Exists(path))
lines = File.ReadAllLines(path, Encoding.Unicode);
if (lines != null)
for (int i = 0; i < lines.Length; ++i)
String str = path2 + @"/" + lines[i];
if (File.Exists(str))
icons.Add(new IconImagesForDummies() { Name = str });
throw new Exception("The Location.txt which stores the location of icons is missing");
if (icons.Count == 0)
throw new Exception("There is no icon image");

Location.txt contains the name of images. My problem is that the program could not find the Location.txt. I have inserted Location.txt in resources. I have to mention that I also used another approach. I made a new folder and instead of
String path = "Resources/Location.txt";
, I used the folder name but it did not work too. What should I do?

Answer Source

If the file is not copied into the output folder of the project, try setting the build action property to content and make sure the copy to output folder property of the file is set to either copy always or copy if newer - depending on the requirements of the project.

Setting the build action as Resource in a WPF Project compiles the file in to the assembly or executable. That is why such a file will not be found in the output folder.

From MSDN:

Resource Files: Data files that are compiled into either an executable or library WPF assembly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download