I've got an absolute path available to me. Say: C:/Program/CoreFiles/Folder1/Folder2/File.txt.
I need to copy that file to C:/Program/Projects/ProjectName/ but it needs to keep Folder1/Folder2/File.txt intact. So the end result should be C:/Program/Projects/ProjectName/Folder1/Folder2/File.txt.
My first attempt at solving this was to try and get the relative path between 2 absolute paths. Found Path.GetRelativePath(string, string) which obviously didn't help as it wasn't meant for WinForms. It would mess up anyway as the final result would be C:/Program/Projects/ProjectName/CoreFiles/Folder1/Folder2/File.txt.
The target directory is empty and I don't know the relative path to copy beforehand other than somehow getting that info out of the absolute path. Since File.Copy won't create folders that don't exist yet, I need to create them first. So how do I get the path that leads up to the file from the CoreFiles directory out of the absolute path?
The only working solution I can come up with is using regex to just replace CoreFiles with Projects/ProjectName in the path string and work with that. But that somehow seems the wrong approach.
Since you can't use Path.GetRelativePath. I suggest looking at another answer that describes how to do this yourself.
Like here...
How to get relative path from absolute path
Using the method in that answer, you can do the rest of your task as shown below.
string sourcePath = "C:/Program/CoreFiles/Folder1/Folder2/File.txt";
string sourceRoot = "C:/Program/CoreFiles/";
string destinationRoot = "C:/Program/Projects/ProjectName/";
// Use built-in .NET Path.GetRelativePath if you can. Otherwise use a custom function. Like here https://stackoverflow.com/a/340454/1812944
string relativePath = MakeRelativePath(sourceRoot, sourcePath);
// Combine the paths, and make the directory separators all the same.
string destinationPath = Path.GetFullPath(Path.Combine(destinationRoot, relativePath));
// Create nested folder structure for your files.
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
// Copy the file over.
File.Copy(sourcePath, destinationPath);
Related
I am trying to upload a file with the sendkeys function on the inputid.
I am currently using the path C:\Users\myusername\Documents\seleniumsolution\Utils\Dir\Dir1\Dir2\Dir3\UploadFolder\example.jpg
I see the file in my solution. But I dont want to give to complete path but only the filename and that selenium finds the path itself. Otherwise I will be the only one that can use this testcase.
I tried with:
var file = Path.Combine(Directory.GetCurrentDirectory(), url);
And tried with:
string documents = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"UploadFolder");
Both of them dont give me the required result.
Hope that you guys can help me out.
You might need to travel on the folders tree to get to the file
AppDomain.CurrentDomain.BaseDirectory
will get you in the bin\debug folder. From there you can use parent to move up to the file location. For example (might need some tweaking)
string solutionParentDirectory = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName;
string file = Path.Combine(solutionParentDirectory, #"UploadFolder\example.jpg");
You can also try
string file = Path.GetFullPath("example.jpg");
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.
Question Background:
I need to copy and paste (move) a file from one folder location to another.
Issue:
The File.Copy method of System.IO requires the that both parameters are of known file locations. I only know one file path location - in this case localDevPath. localQAPath is the folder path where I want the copied file to be moved too.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
File.Copy(localDevPath, localQaPath);
Can anyone tell me how to go about carrying out this 'copy and paste' method I'm trying to implement.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
FileInfo fi = new FileInfo(localDevPath);
fi.MoveTo(Path.Combine(localQaPath, fi.Name));
Assuming that these are user-provided paths and you can't simply include the filename in the second path, then you need to extract the last path element from localDevPath and then add it to localQaPath. You could probably do that with Path.GetFilename.
I'm guessing the issue here is that the filename is variable, in which case, you could do something like this to extract the filename from the full path of localDevPath:
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
string[] tokens = localDevPath.Split(#"\");
localQaPath += tokens[tokens.Length-1];
File.Copy(localDevPath, localQaPath);
Documentation on File.Copy is on MSDN. There is an overload that accepts a boolean, to allow overwriting if there is a naming conflict.
If what you want to do is move the file from one location to another, the method you are looking for is MoveTo. It is a method of the FileInfo class. There is a very complete example in the MSDN Library here: FileInfo.MoveTo Example
I have a program that "greps" out various directory paths from a log text file and prints various results according to the word.
Examples of Directory paths:
C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk
C:/Documents and Settings/All Users/Start Menu/Programs/AccessData
C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier
Therefore how can I grep out the file or folder name after the last "/"? This is to help the program to identify between files and folder. Please do take note of the multiple "." and white spaces found within a directory paths. etc "Imager.exe:Zone.Identifier". Therefore it is difficult to use if(!name.contains()".")
Etc. How to get the "AccessData FTK Imager.lnk" or "AccessData" or "AccessData FTK Imager.exe:Zone.Identifier" from the path STRING?!
May someone please advise on the methods or codes to solve this problem? Thanks!
The codes:
if (!token[7].Contains("."))
{
Console.WriteLine("The path is a folder?");
Console.WriteLine(token[7]);
Console.WriteLine(actions);
MacActions(actions);
x = 1;
}
Use the Path class when working with file paths, and use the File and Directory class when working with actual files and folders.
string str1=#"C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string str2=#"C:/Documents and Settings/All Users/Start Menu/Programs/AccessData";
string str3=#"C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier";
Console.WriteLine(Path.GetFileName(str1));
Console.WriteLine(Path.GetFileName(str2));
Console.WriteLine(Path.GetFileName(str3));
outputs:
AccessData FTK Imager.lnk
AccessData
Zone.Identifier <-- it chokes here because of the :
This class operates on strings, as I do not have those particular files and/or folders on my system. Also it's impossible to determine whether AccessData is meant to be a folder or a file without an extension.
I could use some common sense and declare everything with an extension to be a file (Path.GetFileExtension can be used here) and everything else to be a folder.
Or I could just check it the string in question is indeed a file or a folder on my machine using (File.Exists and Directory.Exists respectively).
if (File.Exists(str2))
Console.WriteLine("It's a file");
else if (Directory.Exists(str2))
Console.WriteLine("It's a folder");
else
Console.WriteLine("It's not a real file or folder");
Use Path.GetFileName.
The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty.
This is to help the program to identify between files and folder
There is no way to determine is a path represents a file or folder, unless you access the actual file system. A directory name like 'Foo.exe' would be perfectly valid, and a file with no extension ('Foobar') would be valid too.
how about tokenized it with "/" like what you're doing ... and then you'll know that the last token is the file, and whatever before it is the path.
You can simply split the whole string by /
e.g.:
string a="C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string[] words=a.split('/');
int len=words.length;
so now words[len] returns the data after last slash(/)..
I hope you understand...
I guess you only have a string that represents the name of the file, if that is the case you can't really be sure. It's totally ok to have a folder namen something like Folder.doc. So if you don't have access to the actual file system it is hard to check. You can get close though using regular expression like:
(.*\\)(.+)(\..*)
Try it on: http://www.regexplanet.com/simple/index.html
If you get any output in group number 3 it's likely that it is a file and not a folder. If you don't get some output try this direct after:
(.*\\)(.+)(\..*)?
That will give you the folder in group 2.
I have an assmebly that will be used in both a desktop app and an asp.net website.
I need to deal with relative paths (local files, not urls) in either situation.
How can i implement this method?
string ResolvePath(string path);
Under a web envronment, id expect the method to behave like this (where d:\wwwroot\mywebsite is the folder iis points at):
/folder/file.ext => d:\wwwroot\mywebsite\folder\file.ext
~/folder/file.ext => d:\wwwroot\mywebsite\folder\file.ext
d:\wwwroot\mywebsite\folder\file.ext => d:\wwwroot\mywebsite\folder\file.ext
for a desktop environment: (where c:\program files\myprogram\bin\ is the path of the .exe)
/folder/file.ext => c:\program files\myprogram\bin\folder\file.ext
c:\program files\myprogram\bin\folder\file.ext => c:\program files\myprogram\bin\folder\file.ext
I'd rather not inject a different IPathResolver depending on what state its running in.
How do I detect which environment I'm in, and then what do i need to do in each case to resolve the possibly-relative path?
Thanks
I don't think the original question was answered.
Let assume you want "..\..\data\something.dat" relative to, lets say the executable in "D:\myApp\source\bin\". Using
System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
will simply return "D:\myApp\source\bin..\..\data\something.dat" which is also easily obtained by simply concatenating strings. Combine doesn't resolve paths, it handles trailing backslashes and other trivialities. He probably wants to run:
System.IO.Path.GetFullPath("D:\myApp\source\bin..\..\data\something.dat");
To get the a resolved path: "D:\myApp\data\something.dat".
The website binaries are copied to a temp folder when the application runs - so you usually can't get the relative path from the excecuting assembly.
This may not be a sensible way of doing this - but what I did to solve this problem was something like this:
if (filepath.StartsWith("~"))
{
filepath = HttpContext.Current.Server.MapPath(filepath);
}
else
{
filepath = System.IO.Path.Combine(Environment.CurrentDirectory, filepath);
}
This is because on the web version - a relative path has a ~ at the front - so I can tell if it's come from the web.config or the App.config.
As mentioned in John's comment, relative to what? You can use System.IO.Path.Combine method to combine a base path with a relative path like:
System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
You can replace Environment.CurrentDirectory in the above line with whatever base path you want.
You could store the base path in the configuration file.