I need to get my application directory and add a file name to that path. So I used it this way.
String kofaxTextFilePath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(File)).CodeBase) + "\\KofaxBatchHistory.txt"
So it will give a path like this.
“file:\\C:\\Documents and Settings\\MyApplication\\ KofaxBatchHistory.txt”
But I need to get only
C:\\Documents and Settings\\MyApplication\\ KofaxBatchHistory.txt
With out doing any thing to this string is there any method to get it directly?
string myDir = System.Reflection.Assembly.GetExecutingAssembly().Location;
myDir = System.IO.Path.GetDirectoryName(myDir);
String kofaxTextFilePath = System.IO.Path.Combine(myDir, "KofaxBatchHistory.txt");
Try Assembly.Location.
Assembly.GetAssembly(typeof(File)).Location
Or (better yet):
typeof(File).Assembly.Location
See Environment.SpecialFolder enumeration, http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx.
You might be looking for SpecialFolder.CommonApplicationData
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;
}
I tried this:
userVideosDirectory = Directory.GetParent(Environment.GetFolderPath
(Environment.SpecialFolder.ApplicationData)).FullName + "\\Videos";
But that give me:
C:\Users\username\AppData\Videos
But I don't have the directory AppData there only:
C:\Users\username\Videos
How do I get the Videos directory without the AppData ?
You can get the videos folder using Environment.SpecialFolders.MyVideos property, and get the actual path to it using the Environment.GetFolderPath method.
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
Note that that enum contains many more folders you can get.
Have you tried this?
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
Something like that:
int userVideosDirectory = (Directory.GetParent(Environment.GetFolderPath
(Environment.SpecialFolder.ApplicationData)).FullName + "\\Videos").IndexOf(#"\AppData\");
if (userVideosDirectory != 0)
{
string str = (Directory.GetParent(Environment.GetFolderPath
(Environment.SpecialFolder.ApplicationData)).FullName + "\\Videos").Remove(userVideosDirectory, #"\AppData".Length);
}
I have an asp.net web app and i need to get the string path of a folder in the same directory as my web app.
Currently im using this code to get the add domain path.
string appPath = HttpRuntime.AppDomainAppPath;
Which returns "c:/path/webapp", i need "c:/path/folder".
Thanks.
If you'd like a more generic approach that doesn't require knowing the starting folder:
//NOTE: using System.IO;
String startPath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath);
Int32 pos = startPath.LastIndexOf(Path.DirectorySeparatorChar);
String newPath = Path.Combine(startPath.Substring(0, pos), "folder"); //replace "folder" if it's really something else, of course
This way, whatever directory your web app is running from, you can get it, reduce it by one level, and tack on "folder" to get your new sibling directory.
You can use String.Replace method.
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
string appPath = HttpRuntime.AppDomainAppPath;
appPath = appPath.Replace("webapp", "folder");
Here is a DEMO.
Thanks to DonBoitnott comments, here is the right answer;
string appPath = #"C:\mydir\anotherdir\webapp\thirddir\webapp";
int LastIndex = appPath.LastIndexOf("webapp", StringComparison.InvariantCulture);
string RealappPath = Path.Combine(appPath.Substring(0, LastIndex), "folder");
Console.WriteLine(RealappPath);
This will print;
C:\mydir\anotherdir\webapp\thirddir\folder
One option would be to do System.IO.Directory.GetParent() a few times. Is there a more graceful way of travelling a few folders up from where the executing assembly resides?
What I am trying to do is find a text file that resides one folder above the application folder. But the assembly itself is inside the bin, which is a few folders deep in the application folder.
Other simple way is to do this:
string path = #"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, #"..\..\"));
Note This goes two levels up. The result would be:
newPath = #"C:\Folder1\Folder2\";
Additional Note
Path.GetFullPath normalizes the final result based on what environment your code is running on windows/mac/mobile/...
if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder
//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
ie,c:\folder1\folder2\folder3
if you want folder2 path then you can get the directory by
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
then you will get path as c:\folder1\folder2\
You can use ..\path to go one level up, ..\..\path to go two levels up from path.
You can use Path class too.
C# Path class
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.
public static string AppRootDirectory()
{
string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(_BaseDirectory, #"..\..\"));
}
Maybe you could use a function if you want to declare the number of levels and put it into a function?
private String GetParents(Int32 noOfLevels, String currentpath)
{
String path = "";
for(int i=0; i< noOfLevels; i++)
{
path += #"..\";
}
path += currentpath;
return path;
}
And you could call it like this:
String path = this.GetParents(4, currentpath);
C#
string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, #"..\..\"));
The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was not found.
public static FileInfo FindApplicationFile(string fileName)
{
string startPath = Path.Combine(Application.StartupPath, fileName);
FileInfo file = new FileInfo(startPath);
while (!file.Exists) {
if (file.Directory.Parent == null) {
return null;
}
DirectoryInfo parentDir = file.Directory.Parent;
file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
}
return file;
}
Note: Application.StartupPath is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.
I use this strategy to find configuration and resource files. This allows me to share them for multiple applications or for Debug and Release versions of an application by placing them in a common parent folder.
Hiding a looped call to Directory.GetParent(path) inside an static method is the way to go.
Messing around with ".." and Path.Combine will ultimately lead to bugs related to the operation system or simply fail due to mix up between relative paths and absolute paths.
public static class PathUtils
{
public static string MoveUp(string path, int noOfLevels)
{
string parentPath = path.TrimEnd(new[] { '/', '\\' });
for (int i=0; i< noOfLevels; i++)
{
parentPath = Directory.GetParent(parentPath ).ToString();
}
return parentPath;
}
}
this may help
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
If you know the folder you want to navigate to, find the index of it then substring.
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.
var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
So, if you want to move 4 up, you just need to change the 1 to 4 and add some checks to avoid exceptions.
Path parsing via System.IO.Directory.GetParent is possible, but would require to run same function multiple times.
Slightly simpler approach is to threat path as a normal string, split it by path separator, take out what is not necessary and then recombine string back.
var upperDir = String.Join(Path.DirectorySeparatorChar, dir.Split(Path.DirectorySeparatorChar).SkipLast(2));
Of course you can replace 2 with amount of levels you need to jump up.
Notice also that this function call to Path.GetFullPath (other answers in here) will query whether path exists using file system. Using basic string operation does not require any file system operations.
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;