Andrey
Andrey

Reputation: 859

C# Can't find file

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!

Upvotes: 1

Views: 30527

Answers (6)

Md Nazrul Islam
Md Nazrul Islam

Reputation: 373

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);

                }

Upvotes: 0

Huynh Triet
Huynh Triet

Reputation: 181

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.

Upvotes: 3

Ria
Ria

Reputation: 10347

  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

Upvotes: 0

Cody Gray
Cody Gray

Reputation: 244732

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.

Upvotes: 6

Vinoth
Vinoth

Reputation: 2439

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");

Upvotes: 0

DROP TABLE users
DROP TABLE users

Reputation: 1955

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?

Upvotes: 0

Related Questions