Jerry Trac
Jerry Trac

Reputation: 367

File Not Found in Directory

Not sure what I am doing wrong. Keeps getting the error that file is not found at the very last line.

string XMLPackagesDir = "C:\\Users\\ro\\Desktop\\Cl\\Cle\\Xm\\";
DirectoryInfo DirInfo = new DirectoryInfo(XMLPackagesDir);
foreach (FileInfo fi in DirInfo.GetFiles("*.*", SearchOption.AllDirectories))
{
XmlSerializer serializer = new XmlSerializer(typeof(Response));
Response i;
FileStream fs = null;
fs = new FileStream("XMLPackagesDir" + fi.Name, FileMode.Open);

Upvotes: 0

Views: 54

Answers (4)

VhsPiceros
VhsPiceros

Reputation: 426

try with

public static void foo(String path) {
            try {
                DirectoryInfo DirInfo = new DirectoryInfo(path);
                foreach (FileInfo fi in DirInfo.GetFiles("*.*", SearchOption.AllDirectories)){
                    XmlSerializer serializer = new XmlSerializer(typeof(Response));
                    Response i;
                    FileStream fs = null;
                    fs = new FileStream(fi.FullName, FileMode.Open);
                }
            } catch (Exception ex) {
                Log.Error(ex);
            }
        }

Upvotes: 0

Steve
Steve

Reputation: 216243

Other answers have given the solution at your typo. But I wish to say that the FileInfo class has a property named FullName, that, as the name explains, contains the full name of the file with its folder name.

So why do you need this string concatenation?

It is just

 fs = new FileStream(fi.FullName, FileMode.Open);

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

you have an object string XMLPackagesDir. But you are using a string on your last line:

fs = new FileStream("XMLPackagesDir" + fi.Name, FileMode.Open);

Use your object, and per best practices, use the Path library:

fs = new FileStream(Path.Combine(XMLPackagesDir, fi.Name), FileMode.Open);

Upvotes: 2

D Stanley
D Stanley

Reputation: 152491

You're using a string literal instead of a variable. Use

fs = new FileStream(XMLPackagesDir + fi.Name, FileMode.Open);

instead of

fs = new FileStream("XMLPackagesDir" + fi.Name, FileMode.Open);

or better yet

fs = new FileStream(Path.Combine(XMLPackagesDir, fi.Name), FileMode.Open);

so you don't have to worry about trailing slashes.

Upvotes: 3

Related Questions