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);
Related
i have the following piece of code:
string fFileName = #txtSelectedFolder.Text + "\\" + file.Name;
txtSelectedFolder.text contains nothing more than a path to a folder (for example: c:\temp\test)
file.name is a FileInfo type where name contains a reference to the current selected file in a collection of Files.
As soon as i use the above code, my fFileName var is filled with an escaped string like c:\\temp\\test\filename.ext
How can i make sure that fFileName contains the unescaped version of the filefolder (and name)
You aren't using a literal when adding in the extra wacks (\) . This will mean your string will escape the \ as it's being compiled and leave you with a single wack.
Alter your line:
string fFileName = #txtSelectedFolder.Text + "\\" + file.Name;
to
string fFileName = txtSelectedFolder.Text + #"\" + file.Name;
You don't need the # literal symbol infront of your variable.
Alternatively:
You can instead use
string fFileName = Path.Combine(txtSelectedFolder.Text, file.Name);
to properly concatenate the file's name to the selected file's path.
You could also use Uri.UnescapeDataString if using .net 5 or older
Read more about it here, example below:
var unescapedPath = Uri.UnescapeDataString("\\\\server\\dir1\\dir2");
Console.WriteLine(unescapedPath);
// \\server\dir1\dir2
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.
I've been trying to do a renamer program in c# for 2 different paths and I keep getting error "Path includes invalid characters" I have no clue how to fix it, I've tried adding # and deleting \ and keeping only one . But still didn't figure out how to fix it. Would love any help.
This is what gives me an error:
if (French.Checked)
{
directoryfile = #"C:\Users\" + curruser + #"\Appdata\Local\fo4renamer\directory.txt";
label1.Text = directoryfile;
readpath = File.ReadAllText(directoryfile);
string shouldwork = readpath + "data";
string french = shouldwork + "\\french";
string german = shouldwork + "\\german";
string tmp = shouldwork + "tmp.txt";
label1.Text = french;
string path2 = #"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\tmp.txt";
string filename = #"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\french.txt";
File.Move(french, german);
}
Here is the whole code:
https://pastebin.com/0i7fzh24
Edit: this is the string for curruser
string curruser = System.Environment.UserName;
The exception was given by this line
File.Move(french, german);
File.ReadAllText Method (String) : Opens a text file, reads all lines of the file, and then closes the file.
So in your scenario :
string french = (Content of directory.txt) + "data" + "\\french";
It depends on content of directory.txt
a) If content = directory path(c:\foo) there is no problem
b) if content = "dummy text *** dummy text" then it will throw exception
Please check content of file
Found the mistake, I used WriteLine instead of Write so it added enter on the end of the line which made the path incorrect, thanks for the help
I have the following code:
if (!Directory.Exists(#"C:\" + reader1.GetString(ColIndex1) + #"\" + reader1.GetString(ColIndex2) + #"\" + reader1.GetString(ColIndex3)))
{
Directory.CreateDirectory(#"C:\" + reader1.GetString(ColIndex1) + #"\" + reader1.GetString(ColIndex2) + #"\" + reader1.GetString(ColIndex3));
}
How do I escape the values so it can correctly check if folders exist and create them if needed?
For example, at the moment, if ColIndex2 contains text which includes the following characters:
\/:*?"<>|
The code does not create the folders properly.
You don't need to check if subdirectories exist . Directory.CreateDirectory will create all subdirectories that you need. For more information check the documentation here.
Creates all directories and subdirectories in the specified path.
Moreover instead of concatening your strings with #"\", the safer way is to use Path.Combine. E.g :
String yourFullPath = Path.Combine(
#"C:\",
reader1.GetString(ColIndex1),
reader1.GetString(ColIndex2),
reader1.GetString(ColIndex3));
// following will do nothing if yourFullPath already exists
Directory.CreateDirectory(yourFullPath) ;
Finally, I've tried this sample with a / character :
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(#"c:\", #"a/b\c")) ;
And it's creating all the folders a, b and c.
EDIT
If you want to removeInvalidcharPath. Path.GetInvalidFileNameChars() will help you to do so :
char [] allInvalidChars = Path.GetInvalidFileNameChars();
string yourPathWithoutInvalidChars = new string(yourFullPath.ToCharArray().Where(c => !allInvalidChars.Contains(c)).ToArray());
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);
}