C# GetFiles from local variable - c#

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 MonitoredFolders 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.

Related

How do I use an illegal character?

public void CreateCertificate()
{
File.Create($"
{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear +
" Certificates- " + certType + "\""}{myFileName}.ppt", 1 ,
FileOptions.None);
}
So I need the backslash between certype and filename to show it belongs within the folder and not next to. It says its an illegal character but how would I get the file in the folder without it?
Based on the code that you wrote the file path that will be generated is (based on my own substitutions for the variables):
String thisYear = "2019";
String certType = "UnderGrad";
String myFileName = "myfile";
String fileToCreate = $"{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear + " Certificates- " + certType + "\""}{myFileName}.ppt";
Debug.Print(fileToCreate);
Will give you this output:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad"myfile.ppt
If you notice there is a " before the filename part of myfile.ppt - This is where the Illegal Character comes from.
If you use this code fragment to generate the path:
String basePath = #"C:\Users\Director\Documents\TestCertApp\TestSub\";
String certificateFolder = $"{thisYear} Certificates- {certType}";
String correctFilePath = Path.Combine(basePath, certificateFolder, $"{myFileName}.ppt");
Debug.Print(correctFilePath);
This will result in the output of:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad\myfile.ppt
This version has a \ where the previous code had a " and is no longer illegal, but conforms to the requirement that you wrote the files being in the folder.
Something else to note:
You may want to use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); to get the path to the MyDocuments folder of the user.
Well, the short answer is that you cannot use an illegal character in a path or file name. Otherwise it wouldn't be illegal. :)
But it seems that the problem here is that you though you were adding a backslash (\) character, when really you were adding a double quote (") character. So if everything else is ok, you can just replace "\"" with "\\" and it should work.
Part of the problem is also that you're doing some strange combination of string interpolation, and it makes the code really hard to read.
Instead you can use just string interpolation to simplify your string (I had to use concatenation below to prevent horizontal scrolling, but you could remove it):
string filePath = $#"C:\Users\Director\Documents\TestCertApp\TestSub\{thisYear} " +
$#"Certificates- {certType}\{myFileName}.ppt";
But even better would be to use the Path.Combine method, along with some variables, to make the intent very clear:
var rootDir = #"C:\Users\Director\Documents\TestCertApp\TestSub"
var fileDir = $"{thisYear} Certificates- {certType}"
var fileName = "{myFileName}.ppt";
var filePath = Path.Combine(rootDir, fileDir, fileName);

Is there a library method to see if a file exists that is cognizant of paths in the PATH environment variable

I have the code below. It works OK but I'm wondering if there is a less verbose way to do it. Is there a library method to see if a file exists that is cognizant of paths in the PATH environment variable such that I can do something like if (FileExistsInAnyPath("robocopy.exe") without having to extract all the paths from PATH
string foundIt = "";
string[] paths = (Environment.GetEnvironmentVariable("Path")).Split(';');
foreach (string path in paths)
{
if (File.Exists((path + "\\robocopy.exe")))
{
foundIt = (path + "\\robocopy.exe");
break;
}
}
if (!string.IsNullOrEmpty(foundIt))
{
// do something with fq path name
Console.WriteLine("found it here: " + foundIt);
}
I think Linq will help you by (using System.Linq)
var paths = (Environment.GetEnvironmentVariable("Path")).Split(';');
var fileName = "robocopy.exe";
var foundit = Path.Combine(paths.SingleOrDefault(f=>File.Exists(Path.Combine(f,fileName))),fileName);
Also, you can wrap that code on your own method FileExistsInAnyPath(string fileName)
but here you need to handle expected exceptions
SingleOrDefault, when there are multiple paths exists. (if you need only the first one you can replace it with FirstOrDefault).
Path.Combine when the LINQ expression returns null. (you can check first by using if(paths.Any(f=>File.Exists(Path.Combine(f,fileName))) before assign to foundit variable.

Having trouble while adding double quotes to a string that is inside a variable in C#?

I am trying to pass a filepath to xcopy command for copying a folder from one location to another( CodedUI using C#).
While doing the same the problems is, I am trying to add double quotes around the path but it's not taking the correct path format.
Code:
string Path = "Some path to folder location";
// Tried all these solutions
Path = '\"' + Path + '\"';
Path = '\"' + Path + '\"';
Path = string.Format("\"{0}\"", Path );
Expected: ""Some path to folder location""
Actual:"\"Some path to folder location"\"
Please help.
In debugger you will see the backslash.
Sent your output to Console and you will see the result is good.
string Path = "Some path to folder location";
Path = "\"" + Path + "\"";
Console.WriteLine(Path);
From what i understand, you want to see
"Some path to folder location"
when you print it. If so, do:
string path = "\"Some path to folder location\"";
or
string path = "Some path to folder location";
var finalString = string.Format("\"{0}\"", path);
Maybe you should try verbatim strings like #"the\path\to\another\location".
This is the best way to write paths without having to struggle with escape codes.
EDIT:
You can use double quotes in a verbatim string:
#"""the\path\to\another\location"""
If you're trying to preserve two sets of double quotes, try building the string like so:
var path = "hello";
var doubleQuotes = "\"\"";
var sb = new StringBuilder(doubleQuotes)
.Append(path)
.Append(doubleQuotes);
Console.WriteLine(sb.ToString()); // ""hello""
Of course, if you want single quotes you simply swap doubleQuotes for singleQuotes = "\""; and get "hello".
To add double quote, you need to add '\' before ' " '.
Note that : if you are having '\' in path, you have to take care of it like below.
if path is "D:\AmitFolder"
string path = #"D:\AmitFolder";
//Or
path = "D:\\AmitFolder"
string str = "\"" + path + "\"";
Console.WriteLine(str);
here str will be "Some path to folder location"
Output:
as in above line we are adding "\"" string as prefix and "\"" as post fix of the main string.
While storing string values if any double quotes are to be added they need to be escaped using backshlash(\). Single quotes are used for character data. The following code should get the output needed.
Path = string.Format("\"{0}\"", Path);
Also I have created a small fiddle here.

How to enter a folder without knowing its name?

I need to read a text file that I know its full path, except one folder's name. I' d use
string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName);
but first, I need to find out unknownFolderName to reach the file' s full path. There is exactly one folder under path, all I need to do is entering under this folder, without knowing its name. How can I achieve this in simplest way?
You could try using Directory.GetDirectories(). If you're guaranteed to only have one folder underneath that folder, then you should be able to do it VIA:
string unknownPath = Directory.GetDirectories(path)[0];
//Now instead of this: [ string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName) ], do this:
string readText = File.ReadAllText(unknownPath + "\\" + itemName);
That should do it. Let me know if it works out for you!
You could use Directory.GetDirectories static method (documentation) which returns the array of strings - full paths to the direcotries in the path you passed to the method. So try something like this (if you are sure that there is at least one directory and you want to use the first one):
string readText = File.ReadAllText(Directory.GetDirectories(path)[0] + "\\" + itemName);
In case you have more than one folder, and you don't know which one is:
Take a look at the following example. You're looking for Windows in the following path: C:\_____\System32\notepad.exe
string path = #"C:\";
var itemName = #"System32\notepad.exe";
var directories = Directory.GetDirectories(path);
foreach (var dir in directories) {
string fullPath = Path.Combine(dir, itemName);
//If you found the correct directory!
if (File.Exists(fullPath)) {
Console.WriteLine(fullPath);
}
}
Use this to get the folder names under your directory:
http://www.developerfusion.com/code/4359/listing-files-folders-in-a-directory/

C# Create multiple .txt files using strings from another file and textbox

I am new to programming. Is there a way to create multiple .txt files using
data from another file in C#.
like this:
1. we have data.txt with 100 or more strings
string1
string2
string3
...
2. we have textbox1 and textbox2 waiting for user to enter strings
3 . we need to create 100 or more files using strings from data.txt and textboxes strings: name of the fisrt file : string1+textbox1string.txt
and inside it we write:
textbox2string + string1 + textbox1string
the same pattern to create other files, second - string2+textbox1string.txt and inside second - textbox2string + string2 + textbox1string
sorry for my english i am not native speaker.
Well, it sounds like you want something like:
string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
File.WriteAllText(line + textbox1.Text + ".txt",
textbox2.Text + line + textbox1.Text);
}
Basically for very simple tasks like this, the methods in the File class allow "one shot" calls which read or write whole files at a time. For more complicated things you generally have to open a TextReader/TextWriter or a Stream.
If this wasn't what you were after, please provide more information. Likewise if you find the code hard to understand, let us know and we'll try to explain. You may fine it easier with more variables:
string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
string newFile = line + textbox1.Text + ".txt";
string fileContent = textbox2.Text + line + textbox1.Text;
File.WriteAllText(newFile, fileContent);
}
EDIT: If you want to add a directory, you should use Path.Combine:
string newFile = Path.Combine(directory, line + textbox1.Text + ".txt");
(You can do it just with string concatenation, but Path.Combine is a better idea.)
Look into the static File class. It will have a lot of what you want.
http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx
Sure...
string textbox1string = textbox1.Text, textbox2string = textbox2.Text;
foreach(string line in File.ReadAllLines("data.txt")) {
string path = Path.ChangeExtension(line + textbox1string, "txt");
File.WriteAllText(path, textbox2string + line + textbox1string);
}

Categories

Resources