C# GetFiles from local variable
I am trying to get a path from SQL, create a variable to store the path, and then use GetFiles to get all of the files in that directory.
I have verified that the path exists and, when I write the result, it shows up correctly. However, I am getting an unknown exception every time it tries to access the directory. Hopefully someone can point out what I am doing wrong.
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
myConnection.Open();
SqlCommand cmd = new SqlCommand("SELECT FolderSource FROM MonitoredFolder开发者_运维知识库s WHERE FolderSource IS NOT NULL", myConnection);
try
{
string returnvalue = (string)cmd.ExecuteScalar();
Console.WriteLine(returnvalue);
Console.ReadLine();
string[] filepath = Directory.GetFiles("@" + "\"" + returnvalue + "\"", "*.*", SearchOption.AllDirectories);
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
myConnection.Close();
You cant dynamically construct a string with using @ token as part of the dynamic string and expect it to work with a literal. @ in literal is interpreted by compiler/runtime
string a = @"abc";
is different from string b = "@abc";
In your example, you should not do "@" + "\"" + ... As the returnvalue is already a string type, you don't need to surround them in quote again and definitely not the "@" too. If in doubt, debug and drag that expression to the watch window. You will see that you ended up with string that looks like "@\"xxxxx\""
Make sure the returnvalue has the correct path value. If in doubt, System.IO.Path class gives you a range of static methods that can help you test or manipulate path string.
Try the application without accessing the database just by executing it with a path that you know works.
string directory = @"C:\temp"
string[] filepath = Directory.GetFiles( directory , "*.*", SearchOption.AllDirectories);
It looks to me as if the first argument of GetFiles is not constructed correctly.
First, try not to do two things in one line of code. It makes debugging very difficult as you have found.
I think you are looking for something like this:
String Dir = "Temp";
String SearchDir = @"\" + Dir + @"\";
Assuming you are trying with a UNC path, please add two back slashes ("\\") before your 'returnValue' variable.
精彩评论