C# move path includes invalid characters - c#

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

Related

StreamReader from .csv - "foreign" chars and blank values showing up as '?'

I'm having two problems with reading my .csv file with streamreader. What I'm trying to do is get the values, put them into variables which I'll be using later on, inputting the values into a browser via Selenium.
Here's my code (the Console.Writeline at the end is just for debugging):
string[] read;
char[] seperators = { ';' };
StreamReader sr = new StreamReader(#"C:\filename.csv", Encoding.Default, true);
string data = sr.ReadLine();
while((data = sr.ReadLine()) != null)
{
read = data.Split(seperators);
string cpr = read[0];
string ydelsesKode = read[1];
string startDato = read[3];
string stopDato = read[4];
string leverandoer = read[5];
string leverandoerAdd = read[6];
Console.WriteLine(cpr + " " + ydelsesKode + " " + startDato + " " + stopDato + " " + leverandoer + " " + leverandoerAdd);
}
The code in and of itself works just fine - but I have two problems:
The file has values in Danish, which means I get åøæ, but they're showing up as '?' in console. In notepad those characters look fine.
Blank values also show up as '?'. Is there any way I can turn them into a blank space so Selenium won't get "confused"?
Sample output:
1372 1.1 01-10-2013 01-10-2013 Bakkev?nget - dagcenter ?
Bakkev?nget should be Bakkevænget and the final '?' should be blank (or rather, a bank space).
"Fixed" it by going with tab delimited unicode .txt file instead of .csv. For some reason my version of excel doesn't have the option to save in unicode .csv...
Don't quite understand the problem of "rolling my own" parser, but maybe someday someone will take the time to explain it to me better. Still new-ish at this c# stuff...

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);

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.

Messagebox does not parse special char :

I'm new to C#, and i'm trying to parse a csv file line by line, to search for a string inside each line and do some action.
My problem is that after reading the line, I used Messagebox.Show("Line: " + CurrentLine); just to check if the output is correct, but while the line should show something like C:\Users\test\Desktop\598\Root\test.xls, it just shows up C (the first char).
I used the same code on a console application and the output is fine.
Is there anything wrong with the Messagebox.Show to show the char : ?
Here is my code:
var reader = new StreamReader(File.OpenRead(Filename));
string Search = "test";
string CurrentLine = reader.ReadLine();
MessageBox.Show("Line: " + CurrentLine);
Thanks

How can I remove a last part of a string with an unknown int?

So, I'm making a file transfer program from one PC in my house to the other. The client can look through the server's files and take what it wants. (Makes it very easy for moving projects/documents/music). This is an example of what a string of a file looks like:
New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"
My problem is removing : "(FILE)-(" + f.Length + " Bytes)".
How can I remove JUST that part from the string? Where the f.Length is unknown...
Thanks!
Just as an alternative to the regex answers, one option is to use LastIndexOf to find the last occurence of a known part of the string (e.g. (FILE)).
var oldString = "ThisIsAString (FILE)-(1234 Bytes";
int indexToRemoveTo = oldString.LastIndexOf("(FILE)");
// Get all the characters from the start of the string to "(FILE)"
var newString = oldString.Substring(0, indexToRemoveTo);
I hope I've got what you want
string contents = "some text (FILE)-(5435 Bytes) another text";
string result = Regex.Replace(contents, #"\(FILE\)-\(\d+ Bytes\)", "");
Console.WriteLine (result);
Prints:
some text another text
Solution to remove everything after .txt
string contents = "some text .txt (FILE)-(5435 Bytes) another text";
string lastSegment = ".txt";
var result = contents.Substring(0, contents.IndexOf(lastSegment) + lastSegment.Length);
Console.WriteLine (result);
prints some text .txt
var match = Regex.Match(pattern: #"\((.*)\)-\(\d+ Bytes\)$", input: name);
if(match.Success)
{
string fileName = match.Groups[1].Value;
}

Categories

Resources