Passing argument surrounded with double quotes - c#

I've read many solutions to this problem and have tried all of them but cannot find the correct way to accomplish this task. My code is:
p.StartInfo.Arguments = path;
I need the path variable to be surrounded by " marks since it is a path to a file that has spaces in the directory names and file name. How can I put a " around the start and end of the path variable? Psudo code would be:
p.StartInfo.Arguments = DoubleQuote + path + DoubleQuote;
As a followup to this situation - once my .exe file received the path - the path was in its entirety following the "\"" suggestions. However, I had to enclose the path in the .exe file code in "\"" so it also could find the .xlsx file since the path and file name had spaces in them. Just wanted to followup with this for anyone else with this situation and wondering why the command line argument was ok, but the .exe file was not finding the file - both apps need enclosed in "\"".

Not sure what solutions you've seen and tried but you need to escape the quotes
p.StartInfo.Arguments = "\"" + path + "\"";
or if you want to use the verbatim string literal (use "" to escape)
p.StartInfo.Arguments = #""" + path + """;
If you have a lot of parameters, you might find the String.Format method easier to maintain.
p.StartInfo.Arguments = string.Format(#"""{0}""", path);

You just need to append the double quote character to the start and end of the string. Creating the double quote can be done in either of the following ways
"\""
#""""

Related

How to change datetime.Now without special characters?

I am exporting a data from SQL Query into CSV and then renaming the csv file into a name-with-date however i have a problem with renaming the csv file to not have any special characters.
I have tried replacing the "." or "/" with an empty space but that does not bear fruitful for me. My code as per below :
string filepath1 = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\import-contacts-" +
DateTime.Now.Date.ToString("yyyy.MM.dd").Replace('/', ' ') + ".csv";
My output should be import-contacts-20190606.csv
However i am getting import-contacts-2019.06.06.csv at the moment.
How can i fix my output?
You can use string interpolation for this, to make it much clearer to read. Also, just don't put anything in the string you don't want...
var filePath = AppDomain.CurrentDomain.BaseDirectory +
$"\\Logs\\import-contacts-{DateTime.Today.AddDays(-1):yyyyMMdd}.csv";
or (if you prefer a 1-liner)...
var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}\\Logs\\import-contacts-{DateTime.Today.AddDays(-1):yyyyMMdd}.csv";
Here's a working example...
https://dotnetfiddle.net/aYAgVr
Note DateTime.Now would work exactly the same, since you're formatting the output to only show the date parts. I'm just pedantic about not using a DateTime for a date!
Just remove . from ToString() method. Try like:
string = AppDomain.CurrentDomain.BaseDirectory + "\Logs\import-contacts-" + DateTime.Now.ToString("yyyyMMdd").Replace('/', ' ') + ".csv";
EDIT (per new req):
DateTime.Now.AddDays(-1).ToString("yyyyMMdd")
The problem is that you're relying on the current culture to provide the right format, but current means different things to different users, and apparently does not produce the format you want.
The solution is simple, use a specific culture to get a specific format:
DateTime.Today.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)
should always use dots as separators.
It will work for you.
string path = string.Format(#"{0}Logs\import-contacts-{1}.csv", new object[] { AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMdd") });

Folder Paths with Spaces

I need to hardcode a file path, but the path contains spaces, so it is not being interpreted properly. I haven't found a workaround that worked :( This is the filepath I need to use but the path is broken at the first space so it reads NetBrain\Personnel\Mangers\Daily which is invalid so it throws an error
oWB = (Excel._Workbook)oXL.Workbooks.Open("\\\\NetBrain\\Personnel\\Managers\\Daily And Weekly Logs\\Mitchell.xls");
Your options are to avoid spaces (because even in this millennium they cause problems in unexpected places), or to quote the names so that they are treated as a single path instead of two or more fragments.
To quote a file path you just need to add double quotes ", like this:
path = "\"" + path + "\"";
Take care not to quote a path that is already quoted.
Most places where you pass a path will not needed the quoted path - it's usually only if a path is passed through a command line interface that it will require quoting.
This may or may not work with the specific Excel example that you posted, as it how it works all depends on how Excel handles the path internally.
Define it in a constant or static variable
const String myPath = #"\\NetBrain\Personnel\Managers\Daily And Weekly Logs\Mitchell.xls"
oWB = (Excel._Workbook)oXL.Workbooks.Open(myPath)
Adding second option with your comment update
Try
const String myPath = #"\\NetBrain\Personnel\Managers\Daily And Weekly Logs\Mitchell.xls"
Uri u = new Uri(myPath);
oWB = (Excel._Workbook)oXL.Workbooks.Open(u.AbsoluteUri);

Add backslash to string

I have a path and I want to add to it some new sub folder named test.
Please help me find out how to do that.
My code is :
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(path+"\test");
The result I'm getting is : "c:\Users\My Name\Pictures est"
Please help me find out the right way.
Do not try to build pathnames concatenating strings. Use the Path.Combine method
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(Path.Combine(path, "test"));
The Path class contains many useful static methods to handle strings that contains paths, filenames and extensions. This class is very useful to avoid many common errors and also allows to code for a better portability between operating systems ("\" on win, "/" on Linux)
The Path class is defined in the namespace System.IO.
You need to add using System.IO; to your code
You need escape it. \t is an escape-sequence for Tabs 0x09.
path + "\\test"
or use:
path + #"\test"
Better yet, let Path.Combine do the dirty work for you:
Path.Combine(path, "test");
Path resides in the System.IO namespace.
There are two options:
Use the # symbol e.g.: path + #"\test"
use a double backslash e.g.: path + "\\test"
string add;
add += "\\"; //or :"\\" means backslash
Backslash '\' is an escape character for strings in C#.
You can:
use Path.Combine
Path.Combine(path, "test");
escape the escape character.
Console.WriteLine(path+"\\test");
use the verbatim string literal.
Console.WriteLine(path + #"\test");
the backslash is an escape character, so use
Console.WriteLine(path+"\\test");
or
Console.WriteLine(path+#"\test");

'u0022' to introduce quotation marks to string C#

I have a string property that returns a directory, it has "program file//" in it, so to use it in a command prompt, I have to use quotation mark around the string. But if I do the following
string myDic = someDic;
string myCmdPrptDic = '\u0022' + someDic + "\u0022'
myCmdPrptDic ends up like \"C://Program Files//myApp\" and will not work under cmd prompt. Is there a way to just create "C://Program Files//myApp" only? Or maybe I should just use a stringBuilder....
I just need to generate a string like:
copy //data/file// "C://program files//myapp"
but I could not do it as
string = "copy //data//file" +" "+ '\u0022' + someDic + "\u0022';
Are you sure that is actually what your string is and not just the way you are viewing it? In the watch window of VS debugger it puts strings in double quotes already which means it needs to escape any quotes inside it. As it stands the above code will not put the \ into your string. If it really is in there (and not just a misreading of the debug information) then there is some other code somewhere adding it in.
Your quotes " and ' are mis-matched.

how to make sure the file name is quoted when it has space

When use Process.startInfo.Arguments, I have filename as one of the argument,
StartInfo.Arguments = filename
I am wondering how to make sure it is correct in the case that filename is "test test".
I would simply always quote it; since "test" is valid too.
I don't know if there is inbuilt file escaping anywhere, but
procStart.Arguments = "blah blip -in \"" + filePath + "\" more args";
should do...
If you wanted you could get fancy with checking the input string (filePath above), but it probably isn't worth checking the edge-cases. For the same reason that if I'm writing TSQL over an unknown table, I'd always add explicit [ / ] (without bothering to check if it needs it).

Categories

Resources