Extract filepath from arbitrary string - c#

I've been attempting to list all filepaths for programs that start on boot. I encountered the following data
Rundll32.exe shell32.dll, ShellExec_RunDLL C:\Users\Name\AppData\Roaming\Oracle\JavaUpdate.exe
"C:\Program Files (x86)\Steam\steam.exe" -silent
This data is from the registry \HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, obtained using following code
foreach(var valueName in registryKey.GetValueNames()){
bootItems.Add(registryKey.GetValue(valueName);
}
Which solution could extract the path from both?
I've attempted to use the following regular expression and variations without any luck.
"^\"([^\"]*)\".*$"

If they only ever look like that then this regex will do the job:
\b.:\\.+?.exe\b
It matches any character followed by a colon and a slash,followed by any text that then ends with .exe where the start/end is either a word break or a start/end of line.

Related

C# automatically substitutes forward-slash with back-slash in path...why?

I have a textbox where I put the name of a file that contains the forward-slash character '/'
When I grab the text from the textbox the '/' is automatically replaced with '\' and it obviously can't find the file, for example:
I write C:\Users\Temp\my/file.txt
I get C:\Users\Temp\my\file.txt
So, instead of opening "my/file.txt", it searches for a directory "my" which contains "file.txt"
How can I solve this?
If you're using Windows (which I assume you are, given the paths in your example), then / is an invalid character for a filename:
The easiest solution here would be to remove the slash from the filename as this is likely to cause further issues down the line.

sony vegas script: probleme to get directory path

I d like to create a blind test generator with a script using Sony vegas 14. For this I must make my script in C#.
I don’t have many experiences in C# so maybe my problem is a very basic one.
To do my script I must use a library class (.dll) and execute my script by Sony vegas. To test my code easily I create a console app where I try my code and can easily print in the console what my code does.
For my program y need to get the path of all subdirectory in a Directory in a string.
My problem is the next one.
the command "Directory.GetDirectories" don't work
When I use the next code to check what in my array/list I get a coherent result if I use it in the console app version on my script (the number of subdirectories in my directory)
string[] dirs = Directory.GetDirectories(myDirectorypath, "", SearchOption.TopDirectoryOnly);// get all directory path in dirs
Console.WriteLine("the number of element in your array is "+ dirs.Length);
List<string> listdedossier = new List<string>(dirs); // convert the array in a list
Console.WriteLine("the number of element in your list is " + listdedossier.Count);
But when in paste my code in my dll project nothing is written in my array or my list. I notice this because when I want to print the number of elements in the list /array that return me 0
.
do you have any idea of what happen i my code?
thanks
You should check the online Microsoft documentation for GetDirectories. The 2nd argument is supposed to be a pattern to search for that conforms to Windows file name patterns. Essentially, all or part of a file name is allowed with * being a wildcard (The .* from regex meaning "match any character any number of times") and ? being a single character wildcard (regex .). You are providing an empty string, so you get nothing back. The pattern *.exe will match all executables in a folder (if you are using GetFiles, while the pattern pattern* matches any files/folders that start with pattern. If you want all directories, do this:
string[] dirs = Directory.GetDirectories(myDirectoryPath, "*", SearchOption.TopDirectoryOnly);
Next point, the path you provide can be either a relative path (e.g., "relative\path\to\folder"), an absolute path (e.g., "D:\path\to\folder"), or a fully qualified domain name (FQDN, e.g. "\servername.gov.edu.com\drive$\path\to\folder"). If you supply a relative path, you'll need to look up Windows' rules for path resolution. It is very easy using a relative path to search the wrong folder, or even a non-existent location (though you should get an exception in that case). Also remember: Windows path names are NOT case-sensitive.
Finally, when writing text with arguments, I HIGHLY recommend you use this format:
Console.WriteLine("The number of elements in your array is {0}", dirs.Length);
This uses a place holder in the string itself which has a numeric value in it. The number indicates what argument after the format string to use (0 is the first argument after the format string). You can use as many placeholders as you want, and use the same place holder in multiple locations. This is a more type-safe way to doing string printing in C# than using the + operator, which requires that an operator be defined that takes a string and whatever type you provided. When you use placeholders, WriteLine will use the built-in ToString method which is defined for all types in the Object class. Placeholders will always work, while using + will only sometimes work.

Using The # symbol for a Directory so two backslashes aren't needed

this seems very simple but upon research I cannot find out how to use the # sign in a directory to prevent it from having to be to backslashes.
An example is of
DirectoryInfo folderInfo = new DirectoryInfo(#"C:\");
But In my Application The directory will be dynamic so I cannot do this:
DirectoryInfo folderInfo = new DirectoryInfo(#Globals.directoryRoute);
So I was wondering what is the correct way to put the # symbol before the string.
Globals.directoryRoute is set as C:\ but the user can change this input so I was hoping instead of having to parse out every double backslash I can use this to make it so only one backslash is needed.
Would this be an effective way of doing it or should I just parse out every second backslash?
The # prefix is a tool to tell the compiler to not take the backslash as an escape character within the following string. If the string is entered at runtime, you don't need to worry about that. So you can just use the content of Globals.directoryRoute as it is.
The double backslashes are only needed for string literals in your code. In memory, only a single backslash is stored in the string, so no # symbol is needed when dealing with strings that are already in memory. Similarly, user input does not need the double backslashes, since it is not interpreted in the same manner as source code. For instance, if you have a text box called txtPath, the user can simply type C:\some\path, not C:\\some\\path as you would normally need to do in source code. When you read the value of that text box in code, you can just use:
string path = txtPath.Text;
This will be the same as if you had the following code:
string path = #"C:\some\path";
or, equivalently:
string path = "C:\\some\\path";

How can I replicate FileSystemWatcher Filter functionality with Regex in C#

I have a single FileSystemWatcher object for a c# project, and multiple patterns to match when events occur.
As a project requirement, I can't create multiple FileSystemObjects and use individual filter methods to match my patterns. So have to have one filter set to *.* to
monitor all files, and when events are created I have to apply a Regex to process matching files per pattern in a loop. My patterns will contain * characters, same as how we pass it to Filter method.
How can I replicate the built in filter functionality with single Regex statement?
Some of the many FileSystemWatcher filter scenarios;
pi*.txt (These should match: piano.txt, pie.txt)
*.doc (Anything with the .doc extension should match)
04*2013.txt (any text file and it should be any day in the month of april)
pi*ar*.jpg (prefix is pi, contains ar after prefix anywhere in the file name and has to be a jpg extension)
pre*ar*pre (any file with pre prefix, followed by ar and followed by another pre)
*.* (Anything is accepted)
Few time back I wrote something similar for my work
public static string WildcardPatternToRegexPattern(string pattern)
{
return string.Format("^{0}$", Regex.Escape(pattern.Replace('/', Path.DirectorySeparatorChar)).Replace(#"\*", ".*").Replace(#"\?", "."));
}
If you are looking to learn regex statements, you can start by looking at http://txt2re.com/. if you paste in a piece of text, there is a point and click interface to generate regex expressions for you. i would also recommend just googling "preg".

How to remove spaces in path?

i have to start process which is placed inside Program Files. But the problem is that Process.Start does not taking space in path.
Process regeditProcess = Process.Start("regedit.exe", "/s C:\\Program Files\\Test Folder\\sample.reg");
Path:
C:\\Program Files\\Test Folder\\sample.reg
there is a space between Program and Files in 'Program Files'.
Thats my problem. How to avoid space?
You should pass command line arguments, containing spaces, in quotes ("), like this:
Process regeditProcess = Process.Start("regedit.exe", "/s \"C:\\Program Files\\Test Folder\\sample.reg\"");
Process.Start is not the problem here, the problem is that regedit.exe doesn't accept spaces in the parameter. Put it into quotes:
Process.Start("regedit.exe", "/s \"C:\\Program Files\\Test Folder\\sample.reg\"");
also, you should use %ProgramFiles% or something equivalent to get the program files folder instead of hardcoding "C:\\Program Files".
You can do something like this to get Program files
Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles)
Here is more detailed code
if(Environment.Is64BitOperatingSystem)
{
Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86)
}
else
{
Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles)
}
The proper thing to do would be to quote the path that contains spaces. So the argument string should be like this:
"/s \"C:\\Program Files\\Test Folder\\sample.reg\""
Though when working with paths, you generally should always use verbatim literal strings.
#"/s ""C:\Program Files\Test Folder\sample.reg"""
Otherwise, you could convert the path using 8.3 names. I don't know of any methods to do this for you in the framework but the rules are simple. If you have a long name that is longer than 6 characters, you take the first 6 non-space characters and append it with tilde (~) followed by a number (usually starting with 1). If multiple files have the same 6 characters, the number is incremented in alphabetical order. So in your case it could be written:
#"/s C:\Progra~1\TestFo~1\sample.reg"

Categories