This question already has answers here:
See if file path is inside a directory
(2 answers)
Closed 9 years ago.
How can I check in C# if the specific path is to directory in "Program Files" ?
C:\Program Files\someDir... -> is in Program Files
D:\Apps\someDir... -> isn't in Program Files
Thanks!
You can check a path in ProgramFiles(x86) by using the code below:
string path = "yourpath";
var programfileX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
if (path.IndexOf(programfileX86, StringComparison.OrdinalIgnoreCase) >= 0)
{
//Found path
}
There're some interseting and subtle issues with the problem:
You should compare paths case insenstive, e.g. "C:\PRogRAM FILES (x86)\Sample" is OK
Separators could be either / or \ so "C:/PRogRAM FILES (x86)/Sample" is OK as well
You should break on separatos only, e.g. "C:\Program Files (x86)MyData\Sample" is not OK
The Code:
public static Boolean PathIncludes(String path, String pathToInclude) {
if (String.IsNullOrEmpty(pathToInclude))
return false;
else if (String.IsNullOrEmpty(path))
return false;
String[] parts = Path.GetFullPath(path).Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar);
String[] partsToInclude = Path.GetFullPath(pathToInclude).Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar);
if (parts.Length < partsToInclude.Length)
return false;
for (int i = 0; i < partsToInclude.Length; ++i)
if (!String.Equals(parts[i], partsToInclude[i], StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
public static Boolean InProgramFiles(String path) {
return PathIncludes(path, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)));
}
// Tests:
// Supposing that ProgramFilesX86 is "C:\Program Files (x86)"
InProgramFiles(#"C:\PRogRAM FILES (x86)\Sample"); // <- true
InProgramFiles(#"C:/PRogRAM FILES (x86)/Sample"); // <- true
InProgramFiles(#"D:/PRogRAM FILES (x86)/Sample"); // <- false
InProgramFiles(#"C:/PRogRAM FILES (x86)A/Sample"); // <- false
First you need to get the program files path. You can do that with System.Environment:
var programFilesPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);
If you want the 32 bit program files path you would just change the special folder you are looking for (System.Environment.SpecialFolder.ProgramFilesX86). Then I would do a contains:
var isInProgramFiles = myPath.ToLower().Contains(programFilesPath.ToLower());
That should get you 90% of the way there at least! Best of luck!
EDIT / Sanitize Note
As a side note - there are situations where you can have a valid input and this still wouldn't match. For example - using "/" instead of "\". If you want to make sure you handle these boundary cases correctly, you can create a "DirectoryInfo" object from your input string, validate that it is actually a folder and also standardize the formatting for it. That code looks something like:
if (!System.IO.Directory.Exists(inputPath)) return false;
var checkPath = (new System.IO.DirectoryInfo(inputPath)).FullName;
In this example "inputPath" is the same as "myPath" was above. That should do a moderately good job of sanitizing the input. Best of luck!
If you have a path variable:
string path = "/* whatever path */";
You can check if it is in a folder subfolder this way:
path.IndexOf('\\' + subfolder + '\\') != -1
Note that in more complex cases .. may revert you out of a subdirectory, meaning that you are not in folder f2 if you have something like this:
"\\base_on_drive\\subfolder\\f1\\f2\\..\\a_file.txt"
The .. will bump you back into it's parent folder f1.
if (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)) || (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)))
{
}
Assuming your program might be running inside of ProgramFiles, you will probably want to get the fullpath of any path you're checking (in case you get a relative path). In addition, C# has a handy SpecialFolder enumeration that you can use to get the ProgramFiles directory.
The following code will take in a path, convert it to a fullpath, and check if the ProgramFiles directory can be found inside of it. You may want to add some error handling (such as checking for null paths).
static string programfileX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
public bool IsInsideProgramFiles(string path)
{
// Get the fullpath in case 'path' is a relative path
string fullPath = System.IO.Path.GetFullPath(path);
return (fullPath.IndexOf(programfileX86, StringComparison.OrdinalIgnoreCase) >= 0);
}
Note: Depending on the systems your code is running in, you may want to check for both SpecialFolder.ProgramFiles and SpecialFolder.ProgramFilesx86.
Credit goes to Toan Nguyen's for the code to get the ProgramFiles directory:
Related
I try to get the Full Path of a File. ie. calc
Input: calc
Expected output: C:\WINDOWS\system32\calc.exe
I could find out how to do it with PowerShell:
(Get-Command calc).Source
Or with CommandLine:
where.exe calc
But unfortunately I can not get it done with C#.
The documentation for Get-Command says:
Get-Command * gets all types of commands, including all of the non-PowerShell files in the Path environment variable ($env:Path), which it lists in the Application command type.
So we will need to get the Path environment variable and iterate over the directories it lists, looking for files with extensions that indicate the file is a program, for example "*.com" and "*.exe".
The problem with the Path environment variable is that it can become polluted with non-existent directories, so we will have to check for those.
The case of the filename and extension don't matter, so case-insensitive comparisons need to be made.
static void ShowPath(string progName)
{
var extensions = new List<string> { ".com", ".exe" };
string envPath = Environment.GetEnvironmentVariable("Path");
var dirs = envPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string d in dirs.Where(f => Directory.Exists(f)))
{
foreach (var f in (Directory.EnumerateFiles(d).
Where(thisFile => extensions.Any(h => Path.GetExtension(thisFile).Equals(h, StringComparison.InvariantCultureIgnoreCase)))))
{
if (Path.GetFileNameWithoutExtension(f).Equals(progName, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(f);
return;
}
}
}
Console.WriteLine("Not found.");
}
static void Main(string[] args)
{
ShowPath("calc");
Console.ReadLine();
}
Output:
C:\WINDOWS\system32\calc.exe
There is always the possibility that the current user does not have permission to list the files from somewhere in the path, so checks should be added for that. Also, you might want to use StringComparison.CurrentCultureIgnoreCase for the comparison.
You can get the Pathenvironment variable, split it with ; as delimiter and loop over that result. Then, check if the file path + #"\" + name + ".exe" exists.
var findMe = "calc";
var pathes = Environment.GetEnvironmentVariable("Path").Split(';');
foreach (var path in pathes)
{
var testMe = $#"{path}\{findMe}.exe";
if (File.Exists(testMe))
{
Console.WriteLine(testMe);
}
}
This outputs :
C:\WINDOWS\system32\calc.exe
I do not know about any way of doing that exact thing from C# either. However the paths are usually well known and can be retreived via the SpecialFolders Enumeration:
using System;
using System.Diagnostics;
using System.IO;
namespace RunAsAdmin
{
class Program
{
static void Main(string[] args)
{
/*Note: Running a batch file (.bat) or similar script file as admin
Requires starting the interpreter as admin and handing it the file as Parameter
See documentation of Interpreting Programm for details */
//Just getting the Absolute Path for Notepad
string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
string FullPath = Path.Combine(windir, #"system32\notepad.exe");
//The real work part
//This is the programm to run
ProcessStartInfo startInfo = new ProcessStartInfo(FullPath);
//This tells it should run Elevated
startInfo.Verb = "runas";
//And that gives the order
//From here on it should be 100% identical to the Run Dialog (Windows+R), except for the part with the Elevation
System.Diagnostics.Process.Start(startInfo);
}
}
}
I did not just use System (37) back then, as I wrote it when x32/x86 Systems were still a thing. You would need to check how it resolves nowadays.
Note that most of those paths are duplicated in the PATH System Variable, so you could look it up: https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/
Path Variables in turn go back to the old DOS days. Basically if you gave the Commandline a command/filename it would try the build-in commands, then Executables in the current working Directory (.bat, .com, .exe), and then go look over the path directories to again look for executeables. And only if all that failed, would it complain.
I finally tried to combine all three answers and came up with this:
I post it here in case someone has the same problem.
public static string[] GetPathOf(string cmd)
{
var list = new List<string>();
list.AddRange(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine).Split(';'));
list.AddRange(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process).Split(';'));
list.AddRange(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.User).Split(';'));
list = list.Distinct().Where(e=>Directory.Exists(e)).SelectMany(e=> new DirectoryInfo(e).GetFiles()).Where(e=>Regex.IsMatch(e.Name,"(?i)^"+cmd+"\\.(?:exe|cmd|com)")).Select(e=>e.FullName).ToList();
return list.ToArray();
}
I am using Directory.CreateDirectory(string) method to create folders, now the problem is if the user enters string as:
"C:\folder1" then it creates the folder in the respective location, fine by me.
but if he writes
"C:\\\\\\\\\\\\\\\\\\\\\\\\\folder1" it is also navigating to the same path, creates folder and not giving any error, this is a problem for me.
So in order to solve the above mentioned problem I try to do some validation before on the path and I tried with Path.GetFullPath() and other Path methods and I see:
Path.GetFullPath("C:\\\\folder1") no exception or error
Path.GetFullPath("C:\\\folder1") exception or error
somehow when the count of backslashes are in even number no exception is thrown but when the count is in odd number then exception is thrown.
How can I achieve this simple thing that when user enters path like:
C:\folder 1 valid path
C:\\\\\\folder1 invalid path
Please let me know if further details are required
Possible solution using FolderBrowserDialog - Users will not manually input the path but rather select/create it via FolderBrowserDialog.
The below code will return all the files in a folder but you can amend it to return whatever information you need.
private void Form1_Load(object sender, EventArgs e)
{
//
// This event handler was created by double-clicking the window in the designer.
// It runs on the program's startup routine.
//
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// We print the number of files found.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
Code found here
If you want to get a proper path from that, maybe you can use the following technique (in addition to what you already have, of course, this is only to remove the repeated backslashes)
Split the path using the '\' character
Remove the empty values (you can filter here the non valid
characters, etc)
Reconstruct the path string using join with the character '\' again
Something like:
pathString = "C:\\\\\\folder1";
splitString = pathString.Split('\\');
nonEmpty = splitString.Where(x => !string.IsNullOrWhiteSpace(x));
reconstructed = string.Join("\\", nonEmpty.ToArray());
Test code here: https://dotnetfiddle.net/qwVqv8
What about sanitizing the path?
char[] separator = new char[] { System.IO.Path.DirectorySeparatorChar };
string inputPath = "C:\\\\\\\folder1";
string[] chunks = inputPath.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string validPath = String.Join(new string(separator), chunks);
I have my program setup to rename and store a file according to checkbox input. I used another stackoverflow post for my template. Only problem is when I tried setting it up for sub-folders, it never puts it in the correct folder. I have a label folder with two sub folders called L-Labels and B-Labels. The user checks which label type it is and the file gets renamed and placed in the according sub-folder. When I used breakpoint my variables are getting the correct value so I don't see what's wrong I have provided my variables and code for relocating the file. What is causing this to not put it in my sub-folder?
Varibales:
string oldPath = lblBrowseName.Text;
string newpathB = #"C:\Users\Public\Labels\B_Labels";
string newpathL = #"C:\Users\Public\Labels\L_Labels";
Method:
if (rChkBoxBizerba.Checked == true)
{
string newFileName = rtxtBoxNewVersion.Text;
FileInfo f1 = new FileInfo(oldPath);
if (f1.Exists)
{
if (!Directory.Exists(newpathB))
{
Directory.CreateDirectory(newpathB);
}
f1.CopyTo(string.Format("{0}{1}{2}", newpathB, newFileName, f1.Extension));
if (System.IO.File.Exists(lblBrowseName.Text))
System.IO.File.Delete(lblBrowseName.Text);
}
I would say this is the problem:
f1.CopyTo(string.Format("{0}{1}{2}", newpathB, newFileName, f1.Extension));
You declare your path but it doesn't have a trailing directory separator, so when you combine all the parts, as above, the actual result is invalid.
You really should use Path.Combine() to combine parts of paths together, this uses the correct directory separator and makes additional checks.
Try something like this:
// Build actual filename
string filename = String.Format("{0}{1}",newFileName, f1.Extension));
// Now build the full path (directory + filename)
string full_path = Path.Combine(newpathB,filename);
// Copy file
f1.CopyTo(full_path);
i am trying to use the various file functions in C# like File.GetLastWriteTime, copy command on the file placed at the path greater than maximum allowed path on windows 7 i.e 260. Its giving me an error on long path name. On MSDN support i they have asked to use the \\?\ before the path. I did the same but still i got the same error, it seems it doesn't make any change. Below is my code. Please let me know if i am using it correct or i need to add any thing:
These all lib i am using as the code is having other things also:
the below is the respective code:
filesToBeCopied = Directory.GetFiles(path,"*",SearchOption.AllDirectories);
for (int j = 0; j < filesToBeCopied.Length; j++)
{
try
{
String filepath = #"\\?\" + filesToBeCopied[j];
File.GetLastWriteTime(filepath);
}
catch (Exception ex)
{
MessageBox.Show("Error Inside the single file iteration for the path:" +
filesToBeCopied[j] + " . The exception is :" + ex.Message);
}
}
where as path is the path to the folder at windows machine starting with drive letter. for ex.: d:\abc\bcd\cd\cdc\dc\..........
Here's a solution for at least the copying portion of your request (thank you pinvoke.net):
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool CopyFile(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
And then to actually copy your file:
// Don't forget the '\\?\' for long paths
string reallyLongPath = #"\\?\d:\abc\bcd\cd\cdc\dc\..........";
string destination = #"C:\some\other\path\filename.txt";
CopyFile(reallyLongPath , destination, false);
As far as I know, you can't access a file directly if its path is too long (by directly, I mean using the methods of File, by creating a FileInfo via the constructor, or by using Directory.GetFiles(string fileName).
The only way I've found that will let you access such a file is to access a directory somewhere in the path before it gets too long, and then programatically walk down the tree until you get to your file, as seen here.
I've taken my code from there and modified it a little to return a FileInfo object for a file with a path that is "too long". Using this code, you can access the necessary properties on the returned FileInfo object (like LastWriteTime). It still has some limitations though, like the inability to use functions like CopyTo() or OpenText().
// Only call GetFileWithLongPath() if the path is too long
// ... otherwise, new FileInfo() is sufficient
private static FileInfo GetFile(string path)
{
if (path.Length >= MAX_FILE_PATH)
{
return GetFileWithLongPath(path);
}
else return new FileInfo(path);
}
static int MAX_FILE_PATH = 260;
static int MAX_DIR_PATH = 248;
private static FileInfo GetFileWithLongPath(string path)
{
string[] subpaths = path.Split('\\');
StringBuilder sbNewPath = new StringBuilder(subpaths[0]);
// Build longest sub-path that is less than MAX_PATH characters
for (int i = 1; i < subpaths.Length; i++)
{
if (sbNewPath.Length + subpaths[i].Length >= MAX_DIR_PATH)
{
subpaths = subpaths.Skip(i).ToArray();
break;
}
sbNewPath.Append("\\" + subpaths[i]);
}
DirectoryInfo dir = new DirectoryInfo(sbNewPath.ToString());
bool foundMatch = dir.Exists;
if (foundMatch)
{
// Make sure that all of the subdirectories in our path exist.
// Skip the last entry in subpaths, since it is our filename.
// If we try to specify the path in dir.GetDirectories(),
// We get a max path length error.
int i = 0;
while (i < subpaths.Length - 1 && foundMatch)
{
foundMatch = false;
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
if (subDir.Name == subpaths[i])
{
// Move on to the next subDirectory
dir = subDir;
foundMatch = true;
break;
}
}
i++;
}
if (foundMatch)
{
// Now that we've gone through all of the subpaths, see if our file exists.
// Once again, If we try to specify the path in dir.GetFiles(),
// we get a max path length error.
foreach (FileInfo fi in dir.GetFiles())
{
if (fi.Name == subpaths[subpaths.Length - 1])
{
return fi;
}
}
}
}
// If we didn't find a match, return null;
return null;
}
Now that you've seen that, go rinse your eyes and shorten your paths.
try with this code
var path = Path.Combine(#"\\?\", filesToBeCopied[j]); //don't forget extension
"\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system.
Important : Not all file I/O APIs support "\?\", you should look at the reference topic for each API
http://www.codinghorror.com/blog/2006/11/filesystem-paths-how-long-is-too-long.html
I recently imported some source code for a customer that exceeded the maximum path limit of 256 characters.
The path you pasted was 285 characters long.
As you noted in your comment, MSDN's link here (http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maximum%5Fpath%5Flength) explains this length in greater detail:
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string" where "" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
With respect to the \\?\ functionality:
Many but not all file I/O APIs support "\?\"; you should look at the reference topic for each API to be sure.
A DirectoryNotFound exception keeps happening for no apparent reason. The exception is thrown in:
public static string[] getKeywords(string filename)
{
string[] keywords = XElement.Load(filename).Elements("Keyword").Attributes("name").Select(n => n.Value).ToArray();
return keywords;
}
BUT it is called in this method:
public static void SyntaxHighlight(SyntaxHighlighter.SyntaxRichTextBox textbox, Language language)
{
switch (language)
{
case Language.Cmake:
textbox.Settings.Comment = "#";
string[] CmakeKeywords = getKeywords("APIs\\cmake.xml");
textbox.Settings.Keywords.AddRange(CmakeKeywords);
break;
case Language.CSharp:
textbox.Settings.Comment = "//";
string[] CSharpKeywords = getKeywords("APIs\\cs.xml");
textbox.Settings.Keywords.AddRange(CSharpKeywords);
break;
case Language.HTML:
textbox.Settings.Comment = "<!";
string[] HTMLKeywords = getKeywords("APIs\\html.xml");
textbox.Settings.Keywords.AddRange(HTMLKeywords);
break;
case Language.Python:
textbox.Settings.Comment = "#";
string[] PythonKeywords = getKeywords("APIs\\python.xml");
textbox.Settings.Keywords.AddRange(PythonKeywords);
break;
}
}
UPDATE:
I have a folder in my project called APIs. I checked the file names several times. Here is the exception: Could not find a part of the path 'C:\Users\Mohit\Documents\Visual Studio 2010\Projects\Notepad\Notepad\bin\Debug\APIs\cs.xml'. Thats the EXACT path of the file!
There's little hope of your program ever finding that folder. When you deploy your app, there is no project folder. The best way to organize it is to add the .xml files to your project with Project + Add Existing. Select them in Solution Explorer and in the Properties window set Build action = None and Copy to Output Directory = Copy if Newer. Build. That puts the files in the same directory as your .exe.
Find them back at runtime with System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
You might have better luck a fully qualified URL (eg #"D:\mypage\APIs\html.xml")
Looks like you are assuming the current directory is the install directory? You should find the directory like...
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) +
Environment.DirectorySeparatorChar +
"file you are looking for".
Are you sure your working directory is the right one? Try to print the absolute path of the . directory. Also, list it's contents and see if that directory really is there.
I'd recommend changing your getKeywords method to be something like this to aid debugging
public static string[] getKeywords(string filename)
{
var file = new FileInfo(filename);
if (!file.Exists)
{
throw new FileNotFoundException("The requested file was not found: " + file.FullName);
}
string[] keywords = XElement.Load(filename).Elements("Keyword").Attributes("name").Select(n => n.Value).ToArray();
return keywords;
}
This should give you the full path at which it was attempting to load the file, which should make the problematic path clear to you.
I tried #nobugz method and it worked. Once you set the properties of each *.xml file to:
The best way to organize it is to add the .xml files to your project with Project + Add Existing. Select them in Solution Explorer and in the Properties window set Build action = None and Copy to Output Directory = Copy if Newer. Build. That puts the files in the same directory as your .exe.
Then put this to get your path for each case in your switch case replacing "filename" with each filename you have.
string[] YourVar = getKeywords(string.Format("{0}\\APIs\\filename.xml", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)));