简体   繁体   中英

C# looks for non-existent file in contents rather than displaying contents

I'm trying file I/O in C# (haven't done so at all before since I'm a beginner). I put a simple text file containing "some text" (literally) in the solution's resources, wrote some code based on online tutorials and pressed F5 to build. I was expecting "some text" to show up in the console window, but an exception did!

Could not find file 'F:\VS\FileTesting\FileTesting\bin\Debug\some text'.

As I said above, "some text" is the content of the file and its name is "important.txt"

Here's the code I'm using:

try
{
     /* using (StreamReader reader = new StreamReader(Properties.Resources.important))
     {
          string line;

          while ((line = reader.ReadLine()) != null)
          {
              Console.WriteLine(line);
          }
     } */
     string contents = File.ReadAllText(Properties.Resources.important);
     Console.WriteLine(contents);
     Console.WriteLine("Contents displayed successfully.");
     Console.ReadKey();
}
catch (Exception e) {
    MessageBox.Show("An error occured. Exception: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

(the commented section above is from another post here , which explained how to read a file line by line)

Based on @JonSkeet's comment below, I think I found the cause: it looks like File.ReadAllText reads and treats the contents of Properties.Resources.important as a filename rather than text as intended. "some text" is the only thing it can find, thus it searches a file with that name in the build directory, which is nonexistent. What I did was rename the original file to "pointer.txt", wrote "important.txt" in it and used it as a pointer to the file I want to read.

I can get away with having it read an external file, but I want the file in my resources. Plus, I can't seem to make it an embedded one - the option is disabled. Does that also have to do anything?

Any help is appreciated.

You do not need to use File methods to read the contents of a resource. The File methods are for reading files from the file system.

To access the contents of the resource, simply write Properties.Resources.important . You can do Console.WriteLine(Properties.Resources.important) to write the contents of the resource to the console.

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