Text file not being found using relative path - c#

I created a text file in my working folder
it's not being picked up in the code
it's only picking up when I use an absolute path
string fileName = "Info.txt";
if (File.Exists(fileName ))
{
Console.WriteLine("File Exists");
Console.WriteLine("File was created " + File.GetCreationTime(fileName));
Console.WriteLine("File was last written to " + File.GetLastWriteTime(fileName));
}
else
{
Console.WriteLine("File does not exist.");
}

File.Exists is looking in the same directory as Directory.GetCurrentDirectory() unless you specify a different path.
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
One reason File.Exists might still return false is if the application lacks access rights to the file
If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

Related

How to get a file full path in c# with Path.GetFullPath

I am trying to get the full path a file by its name only.
I have tried to use :
string fullPath = Path.GetFullPath("excelTest");
but it returns me an incorrect path (something with my project path).
I have read somewhere here a comment which says to do the following:
var dir = Environment.SpecialFolder.ProgramFilesX86;
var path = Path.Combine(dir.ToString(), "excelTest.csv");
but I do not know where the file is saved , therefore I do not know its environment.
can someone help me how to get the full path of a file only by its name?
The first snippet (with Path.GetFullPath) does exactly what you want. It returns something with your project path because the program EXE file is located in the project\Bin\Debug path, which is therefore the "current directory".
If you want to search for a file on a drive, you can use Directory.GetFiles, which will recursively search for a file in a directory given a name pattern.
This returns all xml-files recursively :
var allFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
http://msdn.microsoft.com/en-us/library/ms143316%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/ms143448.aspx#Y252
https://stackoverflow.com/a/9830162/2196124
I guess you're trying to find file (like in windows search), right ?
I'd look into this question - you will find all files that has that string in their filename, and from there you can return full filepath.
var fileList = new DirectoryInfo(#"c:\").GetFiles("*excelTest*", SearchOption.AllDirectories);
And then just use foreach to do you manipulations, e.g.
foreach(string file in fileList)
{
// MessageBox.Show(file);
}
What you're looking for is Directory.GetFiles(), you can read up on it here. The gist of it is, you'll pass in the file path and the file name, and you'll get a string array back. In this instance, you can assume top level with C:\. It should be noted, that if nothing is found, the string array will be empty.
You have passed a relative file name to Path.GetFullPath. Microsoft documentation states:
If path is a relative path, GetFullPath returns a fully qualified path that can be based on the current drive and current directory. The current drive and current directory can change at any time as an application executes. As a result, the path returned by this overload cannot be determined in advance.
You cannot get the same full path name from a relative path unless your current directory is the same each time you invoke the function.

"Could not find a part of the path" error message

I am programming in c# and want to copy a folder with subfolders from a flash disk to startup.
Here is my code:
private void copyBat()
{
try
{
string source_dir = "E:\\Debug\\VipBat";
string destination_dir = "C:\\Users\\pc\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
if (!System.IO.Directory.Exists(destination_dir))
{
System.IO.Directory.CreateDirectory(destination_dir);
}
// Create subdirectory structure in destination
foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
{
Directory.CreateDirectory(destination_dir + dir.Substring(source_dir.Length));
}
foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories))
{
File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "HATA", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
I got an error:
Could not find a part of the path E:\Debug\VipBat
The path you are trying to access is not present.
string source_dir = "E:\\Debug\\VipBat\\{0}";
I'm sure that this is not the correct path. Debug folder directly in E: drive looks wrong to me. I guess there must be the project name folder directory present.
Second thing; what is {0} in your string. I am sure that it is an argument placeholder because folder name cannot contains {0} such name. So you need to use String.Format() to replace the actual value.
string source_dir = String.Format("E:\\Debug\\VipBat\\{0}",variableName);
But first check the path existence that you are trying to access.
There's something wrong. You have written:
string source_dir = #"E:\\Debug\\VipBat\\{0}";
and the error was
Could not find a part of the path E\Debug\VCCSBat
This is not the same directory.
In your code there's a problem, you have to use:
string source_dir = #"E:\Debug\VipBat"; // remove {0} and the \\ if using #
or
string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the # if using \\
Is the drive E a mapped drive? Then, it can be created by another account other than the user account. This may be the cause of the error.
I had the same error, although in my case the problem was with the formatting of the DESTINATION path. The comments above are correct with respect to debugging the path string formatting, but there seems to be a bug in the File.Copy exception reporting where it still throws back the SOURCE path instead of the DESTINATION path. So don't forget to look here as well.
-TC
Probably unrelated, but consider using Path.Combine instead of destination_dir + dir.Substring(...). From the look of it, your .Substring() will leave a backlash at the beginning, but the helper classes like Path are there for a reason.
There can be one of the two cause for this error:
Path is not correct - but it is less likely as CreateDirectory should create any path unless path itself is not valid, read invalid characters
Account through which your application is running don't have rights to create directory at path location, like if you are trying to create directory on shared drive with not enough privileges etc
File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
This line has the error because what the code expected is the directory name + file name, not the file name.
This is the correct one
File.Copy(source_dir + file_name, destination_dir + file_name.Substring(source_dir.Length), true);
We just had this error message occur because the full path was greater than 260 characters -- the Windows limit for a path and file name. The error message is misleading in this case, but shortening the path solved it for us, if that's an option.
I resolved a similar issue by simply restarting Visual Studio with admin rights.
The problem was because it couldn't open one project related to Sharepoint without elevated access.
This could also be the issue: Space in the folder name
Example:
Let this be your path:
string source_dir = #"E:\Debug\VipBat";
If you try accessing this location without trying to check if directory exists, and just in case the directory had a space at the end, like :
"VipBat    ", instead of just "VipBat" the space at the end will not be visible when you see in the file explorer.
So make sure you got the correct folder name and dont add spaces to folder names. And a best practice is to check if folder exists before you keep the file there.

File.Delete isn't working to delete image from sub folder

In our ASP.NET program a user can upload an image to a folder. The location of the image (including the name of the upload folder which is in the root directory) is stored as a variable called "path", ie. "Uploads/fileName.jpg".
To remove the image:
if (File.Exists("~/" + path))
{
File.Delete("~/" + path);
}
However, it fails to run because it can't verify that the file exists. Through some testing we noticed it's looking for "path" in the "system32" directory. Why would this be?
You need to use Server.Map path to ensure that the Tilde is resolved correctly.
MSDN Article is here -> http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Your code would become
var fixedPath = Server.MapPath("~/" + path);
if (File.Exists(fixedPath))
{
File.Delete(fixedPath);
}
The File class is not aware of the IIS directory mapping, so it won't understand ~ correctly. You have to first use a method to map the app relative path to a local path with Server.MapPath

How to get files from ressources folder to copy them in an other directory in C#?

Hello I would like to know if it was possible to extract the files from the ressources folder to copy thme in a directory at the moment i've tried this :
protected void Form1_Load(object sender, EventArgs e)
{
FileInfo info = new FileInfo(file);
info.CopyTo(PATH + "\\shell" + "\\" + file, true);
Bitmap bmp = (Bitmap)Properties.Resources.ResourceManager.GetObject(file);
Image bitmap = Bitmap.FromFile(Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + "ConnectableCORR\\ApplicationConnectTable\\Resources\\teapot.jpg");
bitmap.Save(Path.GetDirectoryName(PATH + "\\shell" + "\\" + "thumbnail_3D.png"), System.Drawing.Imaging.ImageFormat.Png);
}
But the copy isn't working am I doing anything wrong?
Best regards.
The method "Save" of object "Image" requires the name of file in "filename", and you are sending it:
Path.GetDirectoryName(PATH + "\\ shell" + "\\" + "thumbnail_3D.png")
Path.GetDirectoryName
Would return:
PATH + "\\ shell" + "\\"
Would fail the file name, you should also include the file name.
Edit
Try this and check the paths:
FileInfo info = new FileInfo(file);
MessageBox.Show(string.Format("File '{0}' exist '{1}'", info.FullName, info.Exists));
var destinationFile = string.Format("{0}\\shell\\{1}", PATH, file);
info.CopyTo(destinationFile, true);
MessageBox.Show(string.Format("File '{0}' exist '{1}'", destinationFile, File.Exists(destinationFile)));
I'm going to focus on the info.CopyTo() call, as that is the better way of your two options to copy the file. As it is written, there are a number of possibilities as to why it isn't working. For everything I'm thinking about, an exception would be thrown, so you should be able to add a try-catch block around your code and debug to see what the error is. Here's my best guesses, in the order I would try to debug them:
What is file? Is it a filename? Is it a full path plus filename? It looks to me like your code expects it to be fully-qualified in one place and just the name in another.
Source file doesn't exist. I would do a quick info.Exists to confirm that the file exists before trying to copy it.
Make sure the output filename makes sense. If file includes a path, then you really probably want to do info.CopyTo(PATH + "\\shell\\" + info.Name, true) unless you want to include the source path in the output path.
Output directory doesn't exist. If this is the case. A DirectoryNotFoundException will be thrown. Check if the directory exists and create it before doing your CopyTo.
Bad file name. Might contain invalid characters, which will cause either an ArgumentException or a NotSupportedException.
Path too long. Probably not this, but a PathTooLongException would be thrown.

How to ensure all files written are below a given path (prevent directory access)

We have a C# application which will write files to a configurable location. The set of files (and relative paths) is determined at runtime.
We want to ensure that it cannot write files outside the configured location.
For example, the configured location might be c:\Stuff\Export, it would be an error for the program to write anything under C:\Stuff\Important
Really, I think we can achieve this in two ways:
1) Assert none of the relative paths (files to be written) specify 'Parent directory' (typically "../") - System.Path doesn't specify a "parent directory" path component though (like it has for path separation i.e. System.Path.PathSeparator). I feel a bit cludgey checking for "../" in the string.
2) Assert that all of the final absolute paths that are generated (by combining the output location with the file relative path) are relative to i.e. underneath the output location. I'm not exactly sure how to go about this though.
Example usage:
Output directory: c:\Stuff\Export
Output path 1: "foo\bar\important.xls"
Output path 2: "foo\boo\something.csv"
Output path 3: "../../io.sys"
Expected final files
1. c:\Stuff\Export\foo\bar\important.xls
2. c:\Stuff\Export\foo\boo\something.csv
3. Should throw exception
If you create a DirectoryInfo instance on the two paths, its FullName property should return the fully qualified, canonical path. So if you just do that for both of the sides you want to compare, you can do this:
if (chosenDirectory.FullName != configuredDirectory.FullName)
{
throw new InvalidOperationException(
String.Format("Invalid path {0}.", chosenDirectory));
}
Since FullName is just a string, you can do regular string comparison on the paths, like:
if (!chosenDirectory.FullName.StartsWith(configuredDirectory.FullName,
StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidOperationException(
String.Format("Invalid path {0}.", chosenDirectory));
}
You can also use the Parent property and compare its FullName to the chosen directory, if you don't want to allow sub-directories within the configured directory:
if (!chosenDirectory.Parent.FullName.Equals(configuredDirectory.FullName,
StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidOperationException(
String.Format("Invalid path {0}.", chosenDirectory));
}
Here's a quick solution:
string chroot = #"C:\root\child";
string requestedPath = #"..\";
string path = Path.GetFullPath(Path.Combine(chroot, requestedPath));
if (!path.StartsWith(chroot, StringComparison.Ordinal))
throw new Exception("Oops, caught ya!");
edit:
If you want to know if the given path is a valid directory: Directory.Exists(path)

Categories

Resources