When searching a directory for files of a specific name driven by the _fileToSearch
parameter, I then create a custom list of DrawingFound
and store the files path in a string called FileDirectory
.
I then require on a button click OpenDrawing()
for the file stored within FileDirectory
to open to the user. This works in most cases, however, if the path has a ,
for example then the explorer defaults to opening the users documents directory. How can I handle commas within a file path to achieve the desired outcome?
public partial class DrawingFound
{
public string DrawingName;
public string FileType;
public string FileDirectory;
public string Revision;
public void OpenDrawing()
{
Process.Start("Explorer.exe", FileDirectory);
}
}
public void GetDrawings()
{
string _searchFolder = @"C:\Users\ThisUser\Documents";
string _fileToSearch = "Example of file, where a comma is used.txt";
ObservableCollection<DrawingFound> _drawings = new();
DirectoryInfo dirInfo = new(_searchFolder);
FileInfo[] files = dirInfo.GetFiles($"*{_fileToSearch}*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
if (!_drawings.Any(item => $"{item.DrawingName}{item.FileType}" == file.Name))
{
_drawings.Add(new DrawingFound
{
DrawingName = Path.GetFileNameWithoutExtension(file.Name),
FileType = file.Extension,
FileDirectory = file.FullName,
Revision = "- Ignore -"
});
}
}
}
CodePudding user response:
depending on your OS, you may need to use "escaping"
For example, to store a string one "two" three
in a literal delimited with quotation marks, you need to escape the quotation marks. Depending on the language and environment, the "escape character" can be e.g. a \
in this example:
foo = "one \"two\" three"
I hope this helps; otherwise, please be more specific about your language, OS, e.t.c.
CodePudding user response:
After you did your edits, the problem is more clear:
I guess that your OS is windows.
The problem is not with the comma but rather with the space.
The system treats the characters before the space as "file path" and the rest as "parameters." This is for historical reasons.
wrap the entire path in "embedded quotes" so that it is clear to the OS that the entire string is a path. This should prevent it from trying to elide the command parameters out of that string