How to get the full path of a directory - c#

I have create a directory name 'DbInventory' in E drive of my machine
Now in my c# application I want to get the full path of this directoty(DbInventory).
bellow I am mentioning the code I have used
DirectoryInfo info = new DirectoryInfo("DbInventory");
string currentDirectoryName = info.FullName;
But this currentDirectoryName string return the file location in C drive.

First of all, DirectoryInfo constructor takes parameter as a string with full path. When you just write a folder name, it gets the location of your Visual Studio's default path which is most common in your C:/ drive and under Bin/Debug folder.
So in my computer, your currentDirectoryName will be;
C:\Users\N53458\Documents\Visual Studio 2008\Projects\1\1\bin\Debug\DbInventory
If you want to get full path name, you can use Path.GetDirectoryName method;
Returns the directory information for the specified path string.

You are creating with the
new DirectoryInfo("DbInventory");
a new directory on the default drive (C). Take a look at:
MSDN
If you want to get the directory info object of the already created one on drive E you have to specify the path.

You can use Path.GetDirectoryName
DirectoryInfo info = new DirectoryInfo("DbInventory");
string currentDirectoryName = info.FullName;
string directoryPath = Path.GetDirectoryName(path);

try server.mappath
string currentDirectoryName =Server.MapPath(info.FullName);
hope this will work for you

Related

How to set file path to the root of the current directory

I want to save my log file to the root of the current directory.
Right now my file path is
"path": "%temp%\logs\log.txt"
this is working fine but I want to save it to the root of current directory.
For example say my app path is d:\SampleApp\Myapp and I want my log to save to d:\logs\log.txt
the drive 'd' might change on deployment. So want to make it relative of which ever drive is used.
I want to resolve this through appsettings.json, not through coding.
TIA
To set your root folder where you can save a file, you need to have the direction without the root directory and then use the method Combine() from the Path class contained in System.IO.
To get all the drives, you would make use of DriveInfo class
contained in System.IO namespace and their attribute Name to get
the root directory.
For example:
using System.IO;
...
...
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach(DriveInfo x in allDrives)
{
Console.WriteLine(x.Name);
}
// Console: "C:\"
// Console: "D:\"
And then you can combine the root directory path with the file path as following:
Path.Combine(rootPath, filePathWithoutRoot);
To get the root directory of a path, you can use GetPathRoot() method from Path class that's contained in the namespace System.IO. This method returns to you the root directory from a path passed as string argument.
At this page of Microsoft MSDN you can get more information and
this example of how to use it:
string path = #"\mydir\";
string fileName = "myfile.ext";
string fullPath = #"C:\mydir\myfile.ext";
string pathRoot;
pathRoot = Path.GetPathRoot(fullPath); Console.WriteLine("GetPathRoot('{0}') returns '{1}'", fullPath, pathRoot);
// This code produces output similar to the following:
//
// GetPathRoot('C:\mydir\myfile.ext') returns 'C:\'
At this page from the Microsoft MSDN site you can get more information about it:
Path.GetPathRoot Method (String)
Try this (using System.IO):
string root = Path.GetPathRoot(System.Reflection.Assembly.GetEntryAssembly().Location);
Also, You can use Path.GetFullPath() instead Path.GetPathRoot() and remove unwanted part from the string without hardcoding the folder name
And append your folder to it.

C# Application Relative Paths

I just started learning C# and it looks like when you are writing an output file or reading an input file, you need to provide the absolute path such as follows:
string[] words = { "Hello", "World", "to", "a", "file", "test" };
using (StreamWriter sw = new StreamWriter(#"C:\Users\jackf_000\Projects\C#\First\First\output.txt"))
{
foreach (string word in words)
{
sw.WriteLine(word);
}
sw.Close();
}
MSDN's examples make it look like you need to provide the absolute directory when instantiating a StreamWriter:
https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
I have written in both C++ and Python and you do not need to provide the absolute directory when accessing files in those languages, just the path from the executable/script. It seems like an inconvenience to have to specify an absolute path every time you want to read or write a file.
Is there any quick way to grab the current directory and convert it to a string, combining it with the outfile string name? And is it good style to use the absolute directory or is it preferred to, if it's possible, quickly combine it with the "current directory" string?
Thanks.
You don't need to specify full directory everytime, relative directory also work for C#, you can get current directory using following way-
Gets the current working directory of the application.
string directory = Directory.GetCurrentDirectory();
Gets or sets the fully qualified path of the current working directory.
string directory = Environment.CurrentDirectory;
Get program executable path
string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Resource Link 1 Resource Link 2
defiantly, you no need specify full path , what is the good way you perform this type of criteria?
should use relative path #p.s.w.g mention already by comment to use Directory.GetCurrentDirectory and Path.Combine
some more specify by flowing way
You can get the .exe location of your app with System.Reflection.Assembly.GetExecutingAssembly().Location.
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);
on the other hand
Internally, when getting Environment.CurrentDirectory it will call Directory.GetCurrentDirectory and when setting Environment.CurrentDirectory it will call Directory.SetCurrentDirectory.
Just pick a favorite and go with it.
thank you welcome C# i hope it will help you to move forward

Create a folder in Documents C# WPF

I figured how to create a directory in c# wpf. But i do not know how to do it to the current drive folder. Where current drive is the drive windows installed. I used:
Code UPDATED
String cur = Environment.CurrentDirectory;
cur = cur.Substring(0, 2);
string path1 = #""+cur+"\temp";
if(!Directory.Exists(path1))
Directory.CreateDirectory(path1);
But it is giving error saying invalid characters in path. How can i create a folder to another drive?
Thanks!
I'd use the methods available in System.IO.Path. They handle the directory separator for you.
Use Path.GetPathRoot to get the root drive (i.e. c:\\)
var root = Path.GetPathRoot(Environment.CurrentDirectory);
Use Path.Combine to combine two paths into a single directory path:
var temp = Path.Combine(root, "temp");
If all you need is a place to store temporary files, you could consider using:
Path.GetTempPath()

How to get files from a directory with relative path "Directory.GetFiles(sPath) "

I have relative path of a directory like "..\work\FilesDirectory". How to get all files from this directory.
I am currently using the following line of code but it requiresw absolute path.
string []AllFiles = Directory.GetFiles(sPath);
You should you Path.Combine to construct absolute path or you can change Current Directory so relative path points to location you need.
// Building c:\my\home\work\FilesDirectory
var absolutePath = Path.Combine(#"c:\my\home\toys\", #"..\work\FilesDirectory" );
Note: you need to know what location the path is relative to. I.e. if it relative to executable use Assembly.GetEntryAssembly().Location as base path.
If relative path represents your Project Debug folder then you can use:
string relativePath = AppDomain.CurrentDomain.BaseDirectory & "work\FilesDirectory"
Or you can also use config file to save your path and use string.Join() but its better to use Path.Combine instead.
You could always use the Directory.GetCurrentDirectory and the Directory.GetParent methods.
DirectoryInfo parentDirectoryInfo = System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory());
string []AllFiles = Directory.GetFiles(parentDirectoryInfo.FullName);
Hope I helped!

C# Error creating directory in SpecialFolder.LocalApplicationData on Windows 7 as a non Admin

I'm getting the error "Access to the path 'LocalApplicationData\MyProgram\' is denied." when trying to create a directory for my log file. This is when I'm running the program as a non-admin user.
Directory.CreateDirectory(System.Environment.SpecialFolder.LocalApplicationData + "\\MyProgram\\");
Why would this be?
Thanks
LocalApplicationData is just an enum value. You will have to use it in combination with GetFolderPath:
string folder = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"MyProgram");
You're trying to access the enumeration value LocalApplicationData as if it were a string. It's not. You need to find the folder path with GetFolderPath:
string path = Environment.GetFolderPath(
System.Environment.SpecialFolder.LocalApplicationData);
Incidentally, it's better form, and less error-prone, to use Path.Combine to build up paths, rather than doing it by hand:
string path = Path.Combine(#"C:\", "dir"); // gives you "C:\dir"
...and so your code would end up looking like:
string appDataPath = Environment.GetFolderPath
(System.Environment.SpecialFolder.LocalApplicationData);
string path = Path.Combine(appDataPath, "MyProgram");
Directory.CreateDirectory(path);

Categories