1

I have a C# Visual Studio 2008 Form which needs to read the contents of the relative file 'character/attacks.txt' File.Exists() returns false when I run it, even though I'm positive my directories are sorted. Code:

            try
            {
                System.IO.StreamReader file = new System.IO.StreamReader("character/attacks.txt");
                int counter = 0;
                int numberOfLines = 0;
                string line;
                while ((line = file.ReadLine()) != null) { numberOfLines++; }
                string[] attacks = new string[numberOfLines];
                while ((line = file.ReadLine()) != null) { attacks[counter] = line; counter++; }
                file.Close();
                print(attacks.ToString());
            }
            catch (Exception ex) 
            {
                print("ERROR"); print("Did you edit any files?"); print(ex.ToString()); 
            }

Exception Error:

System.IO.FileNotFoundException: Could not find file 'D:\Users\Andrey\Desktop\Turn\character\attacks.txt'.
File name: 'D:\Users\Andrey\Desktop\Turn\character\attacks.txt'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
   at System.IO.StreamReader..ctor(String path)
   at TurnByTurn.Form1.button1_Click(Object sender, EventArgs e) in D:\Users\Andrey\Desktop\C#\TurnByTurn\TurnByTurn\Form1.cs:line 52

I'm porting my code from Python and never had any troubles with this. Thanks in advance!

Andrey
  • 849
  • 5
  • 17
  • 28
  • Are you sure the file exists here: D:\Users\Andrey\Desktop\Turn\character\attacks.txt – Vinoth Aug 02 '12 at 04:15
  • Yes, it does. I even put the characters folder into the debug folder, and it still didn't work. – Andrey Aug 02 '12 at 04:20
  • 1
    Hmm, that's very strange. The computer seems firmly convinced that there is no "attacks.txt" file in the "D:\Users\Andrey\Desktop\Turn\character\" directory, but you say it does. One of you must be wrong. Are you sure that your file actually has a `.txt` extension, not a `.txt.somethingelse` extension? If you have file extensions turned off in the Windows shell, you might be missing this. That's the same problem [this guy had](http://stackoverflow.com/a/2147461/366904). – Cody Gray - on strike Aug 02 '12 at 04:38
  • @CodyGray Thanks! My file was attacks.txt.txt If you added your comment as an answer, I'd mark it. – Andrey Aug 02 '12 at 04:52
  • Glad that worked; I added an answer. – Cody Gray - on strike Aug 02 '12 at 05:04

6 Answers6

6

That's very strange. The computer seems firmly convinced that there is no attacks.txt file in the D:\Users\Andrey\Desktop\Turn\character\ directory, but you say that it definitely exists. One of you must be wrong, and I've learned over the years that computers are right more often than I am.

Are you sure that your file actually has a .txt extension, not a .txt.somethingelse extension? If you have the display of file extensions turned off in the Windows shell, you might be missing this extra file extension. The computer isn't missing it internally, though, and it's seeing that as a totally different file than the one you requested. That's the same problem this guy had.

To re-configure Windows Explorer:

  1. Open the Control Panel folder.
  2. Click on "Folder Options".
  3. Switch to the "View" tab.
  4. Find the "Show hidden files, folders, and drives" radio button in the list of items in the "Advanced settings" list box, and make sure that it is selected.
  5. Click OK.

The other answers to this question do make some good suggestions. Among them:

  1. Make sure that if you use backslashes (which is the standard Windows path separator character) in your string literals, you "escape" them using a second backslash. The reason this is required is that the backslash is interpreted as an escape character by the C# compiler, which allows you to type things like \t to insert a tab. If you want to insert a regular backslash, you have to escape the escape—\\. That's the reason you were getting an error when you tried to use a single backslash.

  2. Instead of escaping the backslash character, you can tell the C# compiler to interpret your string literal exactly as it is typed, including spaces. These are called verbatim string literals. You do this by prefixing the string with the @ character. For example: @"C:\MyDirectory\MyFile.txt"

  3. The reason why the forward slash character that you're using now works is strictly for backwards-compatibility reasons. It isn't the cause of the error (as you can see from the exception message, which includes the path being searched), but it's probably still not a good idea to use forward slashes in paths. As I mentioned above, the backslash is the standard path delimiter in Windows.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
3

This is because you created a text file, so it automatically carried .txt extension. Therefore, if you intentionally add .txt, then the file is now actually attacks.txt.txt.

Huynh Triet
  • 81
  • 3
  • 3
0

I think because your file name has a "\" in it it might be messing it up and telling it to look in the character folder for the attacks.txt file.

edit: or at least it looks like your telling it that your file has a slash in it. Is the file path that it gives you in the error the actual location of the file on your machine?

DROP TABLE users
  • 1,955
  • 14
  • 26
  • I replaced the '/' with an '\' and I got an invalid character error. – Andrey Aug 02 '12 at 04:21
  • you can use the 2 slashes option and also a better practice for finding and using the working directory for your project: `string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); string filename = System.IO.Path.Combine(applicationDirectory, "character\\attacks.txt");` This is just an improvement looks like the double slashes will solve your immediate problem. – DROP TABLE users Aug 02 '12 at 04:35
  • 1
    Why in the world would it be a better solution to use reflection to determine the path of the application's executable file, rather than just using relative paths as he's already doing? – Cody Gray - on strike Aug 02 '12 at 04:36
  • Your right @CodyGray not better, but if for some reason their app was having a problem finding the file could this be a different way to get to the path? – DROP TABLE users Aug 02 '12 at 04:46
  • Nope, it's going to end up doing exactly the same thing. Unless, of course, the working directory was not the same as the application directory. Which is certainly possible in theory, but that is not the case here, as you can see from the exception message, which includes the file path. Anyway, hard-coding paths is not a good idea anyway, so it doesn't make too much sense to quibble over the "right" or "best" way of doing it! – Cody Gray - on strike Aug 02 '12 at 05:06
0

Yeah if you replace the '/' with an '\' u ll get an invalid character error. Try this with 2 slashes

System.IO.StreamReader file = new System.IO.StreamReader("character\\attacks.txt");

or

System.IO.StreamReader file = new System.IO.StreamReader(@"character\attacks.txt");
Vinoth
  • 2,419
  • 2
  • 19
  • 34
0
  1. Path splitter in Posix is / and in Windows is \.
  2. Use Directory.GetCurrentDirectory to make sure the current directory is correct.
  3. If current directory is not correct use full path or change current directory by Directory.SetCurrentDirectory
Ria
  • 10,237
  • 3
  • 33
  • 60
0

This will work fine...

 string fileName = file_name+".pdf";
                string files = System.IO.Path.Combine("pdf/") + fileName;
                if (!System.IO.File.Exists(files))
                {
                    return RedirectToAction("index", new { message = "File Not Found" });

                }
                else
                {

                    byte[] fileBytes = System.IO.File.ReadAllBytes(files);
                    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, files);

                }
Md Nazrul Islam
  • 363
  • 4
  • 13