I'm trying to set a default-folder when I open my ExplorerBrowser.
if (Direcory.Exists(folderPath))
{
var folderPathFile = ShellFile.FromFilePath(folderPath);
Eb.ExplorerBrowserControl.Navigate(folderPathFile);
}
Funny thing that the method throws an "FileNotFoundException" even if Directory.Exists returns true.
The FromFilePath-Method looks like:
internal ShellFile(string path)
{
// Get the absolute path
string absPath = ShellHelper.GetAbsolutePath(path);
// Make sure this is valid
if (!File.Exists(absPath))
throw new FileNotFoundException(string.Format("The given path does not exist ({0})", path));
ParsingName = absPath;
Path = absPath;
}
I'm not quite sure what "GetAbsolutePath(path)" does, but my path already is absolute. Does it maybe destroy my functional path by calling this method? How can I solve this issue?
The folderPath variable, when passed to Directory.Exists() returns true, so this is a directory path (file paths passed to this method return false).
This same value is passed into ShellFile.FromFilePath(), the absolute value of the path is obtained, and this is then passed into File.Exists -- but, as above, it is a directory path, hence false is returned.
Related
static void SendMail()
{
String SystemErrors = DateTime.Now.ToString("d");
String filepath = #"C:\Windows\Boot\";
string filepath2 = filepath + #"\SystemErrors\somefile.text";
{
if (!Directory.Exists(filepath2))
Directory.CreateDirectory(#"c:\Windows\Boot\SystemErrors\somefile.txt");
if (!File.Exists(filepath2))
File.Create(filepath2);
}
Im trying to create a new folder and file.text, but nothing seems to work.
I don't think you're using the Exists methods correctly.
You must call File.Exists when you want to check if a file exists, and you must provide the path to the file.
Directory.Exists must be called when you want to check if a directory exists, and you must provide the path to the directory.
In my current program, I have the main method which contains
using (NetworkShareAccessor.Access(---credentials etc---)
{
(string latest = new DirectoryInfo(---folder on the network---).GetDirectories().OrderByDescending(d => d.LastWriteTimeUTC).First().ToString();
CopyFiles(latest, "---folder---", "---file name---");
}
This successfully accesses the network folder, and I know because if I choose to Console.WriteLine(latest), it outputs the correct folder to the console, proving that the fodler has been accessed. However, in my CopyFiles method, I get the unhandled exception which states:
Access to the path '---path location---' is denied
I need to use the external method and can't simply put it all in Main() because it will be used elsewhere and repeated, so it makes more sense to have it's own method and pass in different parameters which contain a folder name and a file name.
I have already tried putting everything within the CopyFiles method within it's own using statement which I have used in the Main Method, but this doesn't work either. FYI here is the code used in the CopyFiles Method
static void CopyFiles(string mostRecentFolder, string installerFolder, string installerName)
{
string sourcePath = string.Format(#"\\---network directory---\{0}\{1}", mostRecentFolder,
installerFolder, installerName);
string targetPath = string.Format(#"C:\Temp\");
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
string sourceFile = Path.Combine(sourcePath, installerName);
string destFile = Path.Combine(targetPath, installerName);
File.Copy(sourcePath, destFile, true);
}
You have:
File.Copy(sourcePath, destFile, true);
Try:
File.Copy(sourceFile, destFile, true);
Try including your file name in the path, this seems to be the reason for your error.
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:
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);
How can I check if the directory exists with a dynamic path (~) not a fixed path (C:)?
My code:
Soin_Id = Request.QueryString["SoinId"];
string path = #"~\Ordo\Soin_"+Soin_Id+#"\";
if (Directory.Exists(path))
{
ASPxFileManager_Ordo.Settings.RootFolder = path;
}
else
{
ASPxFileManager_Ordo.Settings.RootFolder = #"~\Ordo\";
}
With this condition, it's never true, even though the directory exists.
You need to use Server.MapPath to resolve dynamic path to physical path on server.
if (Directory.Exists(Server.MapPath(path)))
also consider using Path.Combine for concatenation of path.