-6

Can any one suggest to me the best way to see if a file exists? File.Exists is not working for me.

string abc = "me_label.deploy";
File.Exists(abc)

The file, abc, is coming from Streamreader.ReadLine();.

I even used the full path. I don't want to include files in my project. If I include it in my project it is working fine.

My code:

FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("me@localhost/"; + ab);
//ab=newfolder/newfolder1
ftp.Credentials = new NetworkCredential(user, pass);
ftp.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader sr = new StreamReader(ftp.GetResponse().GetResponseStream());
StringBuilder result = new StringBuilder();
string abc = sr.ReadLine();
while (abc != null)
{
    result.Append(abc);
    //abc=file
    result.Append("\n");
    if (File.Exists(ab+abc))
    {
        //file
    }
} 
Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
user2155670
  • 9
  • 1
  • 1

1 Answers1

5

Any relative path in .NET is by default relative to the bin/Debug subdirectory of your project. So, unless me_label.deploy is in that folder, your program will not be able to find it. If you include it, it is copied to that folder and then it works.

But you have to make the path absolute instead. Use the methods from the Path class.

string filename = "me_label.deploy";
string basePath = @"C:\My Documents\";
string absolutePath = Path.Combine(basePath, filename);
// C:\My Documents\me_label.deploy
Console.WriteLine(File.Exists(absolutePath));
Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
  • +1. But I would substitute `Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)` for `basePath`. – ispiro Apr 18 '13 at 19:04
  • Its working fine if i include it in my project, i want it to download newly, i dont want to add those files to my project. I want it to check from ftp link only. – user2155670 Apr 18 '13 at 19:09
  • @ispiro I agree, but it was just any random path off the top of my head. I don't know where the OP has stored this file. – Daniel A.A. Pelsmaeker Apr 18 '13 at 19:10
  • FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://me@localhost/" + ab); //ab=newfolder/newfolder1 ftp.Credentials = new NetworkCredential(user, pass); ftp.Method = WebRequestMethods.Ftp.ListDirectory; StreamReader sr = new StreamReader(ftp.GetResponse().GetResponseStream()); StringBuilder result = new StringBuilder(); string abc = sr.ReadLine(); while (abc != null) { result.Append(abc); //abc=file result.Append("\n"); if (File.Exists(ab+abc)) { //file }} – user2155670 Apr 18 '13 at 19:21
  • @user2155670 Please combine `ab` and `abc` using the technique I show. – Daniel A.A. Pelsmaeker Apr 18 '13 at 20:37