1

firstly apology if this has already been answered and I am duplicating the question. I have tried to find the answer to my issue but have failed and none of the auto-suggestions answers my problem. I have my main project (XAML) and also a class library project called FileStore for files. The class library project is referenced into the main project and I have images and icon file in the class library project that I can access with no issues in my main project, however, I struggle to get the content of a txt file from the CL project to display in a label on the main project. I get the error: the system could not find the file and from the error, I can see that it is trying to look for a file in the main project bin\debug folder

I tried to follow this previous post which seemed to partly answer my issue but to no avail sadly. Get relative file path in a class library project that is being referenced by a web project

The txt file Build action is set to: Resource and Copy to Output Directory set to: Copy Always. As I mentioned I have the FileStore project referenced in my main project and the images work fine. Below is the code I am using, I have tried different variations such as: \Resources\textFile.txt and \textFile.txt, still no luck. '''

   public static string ReadFileinClLibr()
    {
        var buildDir = 
       Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        var filePath = buildDir + @"\textFile.txt";
        return File.ReadAllText(filePath);
    }

''' For comparition here is the path for the image files that works, but I cannot get it to work with the txt file, as the error reads: the given paths format is not supported.. '''

   @"pack://application:,,,/FileStore;component/Resources\textFile.txt"

''' I want to be able to input the content of the text file from the class library project to the label in the main xaml project. At the moment compiler keeps looking for this file in a debug folder of the main project, what I want is, for the compiler to look for the txt file in a CL FileStore project

Behemot
  • 73
  • 1
  • 5
  • Isn't this a run-time error? Cause you are saying that the compiler is complaining. Does it pop in the visual studio error window or when you run the application with f5 or through the compiled binaries? – Kristóf Tóth Jul 23 '19 at 12:20
  • @KristófTóth the error only occurs when the ReadFileinClLibr() is invoked. This method is invoked when a button event handler is called which contains this method. I don't get any other errors otherwise, so when I hit F5 the whole application runs fine until I select the button to call the ReadFileinClLibr() method. apology for misleading wording in my post. – Behemot Jul 23 '19 at 12:39

2 Answers2

0

In order to access the file all the time, we have to have the file copied to the debug folder. Right click the file from solution explorer change the properties then try to access the file from the executing assembly location.

enter image description here

StringBuilder bodyContent = new StringBuilder();    
string fileName = "myfile.txt";
try
{
  string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
  using (StreamReader sr = new StreamReader(filePath))
  {
    // Read the stream.
    bodyContent.Append(sr.ReadToEnd());
  }
}
catch(Exception ex)
{
   Console.WriteLine(String.Format("{0} @ {1}", "Exception while reading the file: " + ex.InnerException.Message, DateTime.Now));
   throw ex;
}
Sreekanth
  • 385
  • 1
  • 6
  • 17
  • Thank you, sadly it is still not working. below the error message: Could not find file: "C:\\Users\\user\\source\\repos\\App-Name\\bin\\Debug\\Textfile.txt". I have also manually checked and the file is not there, so is not being copied. I have set the Build Action on the file to 'Content' as per your screenshot and changed the Copy output directory to 'Copy when newer'. it looks as during the run it cannot find the file in the library project for some reason.. – Behemot Jul 23 '19 at 16:05
  • Where is your resource file available? If you added the file in class library project and then trying to access the file in your application by referencing the class library in the project. In that case first you have to have resources embedded in to the project and made available publicly to access from outside, please if following post from stackoverflow helps you out. https://stackoverflow.com/questions/3032592/resources-at-class-library-project – Sreekanth Jul 24 '19 at 03:06
0

Thanks to the post from @Sreekanth Gundlapally I have managed to fix my issues. I have mostly drawn on from the answer provided by @Sreekanth Gundlapally but there is one important bit missing. The string fileName should include any subfolders that the resource file is within in the Class Library Project, for example in my case the folder was named 'Resources' so the code should look like this:

string fileName = @"Resources/myfile.txt";
try
{
  string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
  using (StreamReader sr = new StreamReader(filePath))
  {
    // Read the stream.
    bodyContent.Append(sr.ReadToEnd());
  }

I have also cleaned and rebuilt solution after which it all worked a charm.

Also a side note, anyone trying this and getting funny characters make sure your file's encoding is set to UTF-8 as this is the default encoding used by StreamReader, otherwise your file content may not be read correctly if it contains signs such as apostrophe.

Behemot
  • 73
  • 1
  • 5