I am working on Unit tests that test a method in an application that produces a file. So I decided to put an expected file in a directory called Resource/Empower/.
The resource folder is at the same level as the bin folder of the Unit Test project.
Now what I want to do is get the path of the file name. I cannot hard code because I don't know exactly about the drives on the build server.
So how do I get the relative path of the file. Lets say if the file Name is expectedMasterFileSetUp.txt?
I want the path Resource/Empower/ExpectedMasterFileSetUp.txt
Why use a URI?
string AbsolutePathRelativeToEntryPointLocation( string relativePath )
{
Assembly entryPoint = Assembly.GetEntryAssembly() ;
string basePath = Path.GetDirectoryName( entryPoint.Location ) ;
string combinedPath = Path.Combine( basePath , relativePath ) ;
string canonicalPath = Path.GetFullPath( combinedPath ) ;
return canonicalPath ;
}
Use Path.GetDirectoryName() on the result of
new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath
then Path.Combine() your relative path onto the end.
Related
it is my path example E:\test\img\sig.jpg
I want to get E:\test\img to create directory
i try split but it be img
so I try function Directory.CreateDirectory and the path is E:\test\img\sig.jpg\
say me a ideas?
The recommended way is to use Path.GetDirectoryName():
string file = #"E:\test\img\sig.jpg";
string path = Path.GetDirectoryName(file); // results in #"E:\test\img"
Use Path.GetDirectoryName which returns the directory information for the specified path string.
string directoryName = Path.GetDirectoryName(filePath);
The Path class contains a lot of useful methods for path handling, which are more reliable than manual string manipulation:
var directoryComponent = Path.GetDirectoryName(#"E:\test\img\sig.jpg");
// yields `E:\test\img`
For completeness, I'd like to mention Path.Combine, which does the opposite:
var dirAndFile = Path.Combine(#"E:\test\img", "sig.jpg");
// no more checking for trailing slashes, hooray!
To create the directory, you can use Directory.Create. Note that it is not necessary to check if the directory exists first.
You can try this code to find the directory name.
System.IO.FileInfo fi = new System.IO.FileInfo(#"E:\test\img\sig.jpg");
string dirname = fi.DirectoryName;
and to create the directory
Directory.CreateDirectory(dirname );
Another solution can be :
FileInfo f = new FileInfo(#"E:\test\img\sig.jpg");
if (f.Exists)
{
string dirName= f.DirectoryName;
}
Here's my code in moving excel file to be specific..
if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
{
//Move files to history folder
string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
foreach (string s in files)
{
var fName = Path.GetFileName(s); //12232015.xls
var sourcePath = Path.Combine(destinationPath, fName);
var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
File.Move(fName, destFile);
}
}
But it gets an error of
Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.
Why it finds under my project not on the specific folder i set?
Thank you.
You're only using the name of the file:
var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);
Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.
You should use the entire path for the source file:
File.Move(sourcePath, destFile);
Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.
There is an Logical error. Change
File.Move(fName, destFile);
to
File.Move(sourcePath, destFile);
as fName only contains file name and not fullpath. The file is checked in working directory.
I was using hard-coded directory path to Program Files to move file. I would now like to use the correct method to find the folder in Program Files.
I have found this method doing some Googling and it is what i would like to use:
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
I unfortunately am not sure how to implement and use this method.
Where do i insert the method in my app?
How do i use the above instead of this:
if (File.Exists(#"C:\PROGRA~1\TEST\ok.txt"))
File.Delete(#"C:\PROGRA~1\TEST\ok.txt");
File.Copy(#"C:\PROGRA~1\PROGRAMFOLDER\ok.txt", #"C:\PROGRA~1\TEST\ok.txt");
It's much easier to get the special folders like Program Files using
Environment.SpecialFolders
string programFilesFolder =
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
Continuing that example you could do something like this
string pathToFile =
Path.Combine(programFilesFolder, #"TEST\ok.txt");
if (File.Exists(pathToFile))
File.Delete(pathToFile);
UPDATE
Modified the code example to always get the 32-bit Program Files folder whether you're running 32- or 64-bit OS as #Mario pointed out that's what your original code was doing.
string fileName = Path.Combine( ProgramFilesx86(), applicationPath, #"ok.txt");
if (File.Exists( fileName ) )
{
File.remove( fileName );
}
string sourceFile = Path.Combine( ProgramFilesx86(), #"\PROGRAMFOLDER", "ok.txt" );
File.Copy( sourceFile, fileName);
Edit:
You should not use this method. The program folder depends on the capability of the programs and not the system! You must know whether they install to the ProgramFiles or ProgramFilesX86 folder.
And then use Eric J.'s answer.
string sourceFolder =
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
string source =
Path.Combine(sourceFolder, #"ok.txt");
string targetFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string target = Path.Combine(targetFolderPath, #"ok.txt");
if (File.Exists(source))
File.Delete(source);
File.Copy(targetFolderPath, source);
I need to the the bin path of the executing assembly.
How do you get it?
I have a folder Plugins in the Bin/Debug and I need to get the location
Here is how you get the execution path of the application:
var path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
MSDN has a full reference on how to determine the Executing Application's Path.
Note that the value in path will be in the form of file:\c:\path\to\bin\folder, so before using the path you may need to strip the file:\ off the front. E.g.:
path = path.Substring(6);
You could do this
Assembly asm = Assembly.GetExecutingAssembly();
string path = System.IO.Path.GetDirectoryName(asm.Location);
This is what I used to accomplish to this:
System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");
var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;
Path.GetDirectoryName(Application.ExecutablePath)
eg. value:
C:\Projects\ConsoleApplication1\bin\Debug
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");
Application.StartupPath
This is how you can access the bin / debug path
string parentDirName = new FileInfo(AppDomain.CurrentDomain.BaseDirectory).Directory.Parent.FullName;
I have some xml files, which are used in my application. They are stored in the same folder with application , in subfolder DATA: "C:\MyProject\DATA\".
To get the DATA folder path i use this code :
static public string GetDataFolderPath()
{
string s = System.IO.Directory.GetCurrentDirectory().Replace(#"\bin\Debug", "");
int i = s.LastIndexOf(#"\");
s = s.Substring(0, i);
i = s.LastIndexOf(#"\");
s= s.Substring(0, i);
return s + #"\Data\";
}
So when i want to deploy my application, i create a setup project, and add the DATA folder to Application folder. But after i install the program f.e. "C:\Project"(DATA folder- "C:\Project\DATA" i got the error: "folder C:\DATA is not found".
What i need to change to make things working after deployment. Why it looks for the DATA folder on 1 level higher?
Try this, it might work better:
public static string GetDataFolderPath()
{
#if DEBUG
// This will be executed in Debug build
string path = Directory.GetCurrentDirectory().Replace(#"\bin\Debug", "");
#else
// This will be executed in Release build
string path = Directory.GetCurrentDirectory();
#endif
return Path.Combine(path, "Data");
}
Or just this if you want one for both Debug and Release builds:
public static string GetDataFolderPath()
{
string path = Directory.GetCurrentDirectory().Replace(#"\bin\Debug", "");
return Path.Combine(path, "Data");
}
You have to add using System.IO; for this to work.
Maybe current directory (during launching your program) is not the same one that assemblies lie?
try:
//get the full location of the assembly
string fullPath = System.Reflection.Assembly.GetAssembly(typeof(<your class name>)).Location;
//get the folder that's in
string theDirectory = Path.GetDirectoryName( fullPath );
or
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);