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()
Related
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
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
There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.
The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:
Process.Start("Textfile.txt");
So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.
Edit:
If I change above code to this, would it work?
string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
Windows needs to know where to find the file, so you need somehow specify that:
Either using absolute path:
Process.Start("C:\\1.txt");
Or set current directory:
Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");
Normally CurrentDirectory is set to the location of the executable.
[Edit]
If the file is in the same directory where executable is you can use the code like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
The way you are doing this is fine. This will find the text file that is in the same directory as your exe and it will open it with the default application (probably notepad.exe). Here are more examples of how to do this:
http://www.dotnetperls.com/process-start
However, if you want to put a path in, you have to use the full path. You can build the full path while only caring about the relative path using the method listed in this post:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/e763ae8c-1284-43fe-9e55-4b36f8780f1c
It would look something like this:
string pathPrefix;
if(System.Diagnostics.Debugger.IsAttached())
{
pathPrefix = System.IO.Path.GetFullPath(Application.StartupPath + "\..\..\resources\");
}
else
{
pathPrefix = Application.StartupPath + "\resources\";
}
Process.Start(pathPrefix + "Textfile.txt");
This is for opening a file in a folder you add to your project called resources. If you want it in your project root, just drop off the resources folder in the above two strings and you will be good to go.
You'll need to know the current directory if you want to use a relative path.
System.Envrionment.CurrentDirectory
You could append that to your path with Path
System.IO.Path.Combine(System.Envrionment.CurrentDirectory, "Textfile.txt")
Try using Application.StartupPath path as default path may point to current directory.
This scenario has been explained on following links..
Environment.CurrentDirectory in C#.NET
http://start-coding.blogspot.com/2008/12/applicationstartuppath.html
On a windows box:
Start notepad with the file's location immediately following it. WIN
process.start("notepad C:\Full\Directory\To\File\FileName.txt");
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);
Relative paths in C# are acting screwy for me. In one case Im handling a set of Texture2d objects to my app, its taking the filename and using this to locate the files and load the textures into Image objects. I then load an image from a relative path stored in the class file and use a relative path that needs to be relative to Content/gfx. But if i dont load these textures these relative paths will fail. How can I garuantee that my rel path wont fail? In web work all rel paths are relative to the folder the file we're working from is in, can I set it up this way and make all rel paths to root folder where my app is located?
I recommend not using relative paths in the first place.
Use Path.Combine to turn your relative paths into absolute paths. For example, you can use this to get the full path to your startup EXE:
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Once you have that, you can get it's directory:
string exeDir = Path.GetDirectoryName(exeFile);
and turn your relative path to an absolute path:
string fullPath = Path.Combine(exeDir, "..\\..\\Images\\Texture.dds");
This will be much more reliable than trying to use relative paths.
If you are expecting a resource to be in the same directory as the executable file or in a sub directory of that directory, it's best to always use
string fullPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), subPath);
or if you are worried that the working directory might be wrong you can do this:
string fullPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), subPath);
// [name space] is name space
//you should copy your file.-- into Depug file
string path = (Assembly.GetEntryAssembly().Location + "");
path = path.Replace("name space", "filename.--");
// [WindowsFormsApplication4] is name space
//you should copy your "mysound.wav" into Depug file
//example::
string path_sound = (Assembly.GetEntryAssembly().Location + "");
path_sound = path_sound.Replace("WindowsFormsApplication4.exe", "mysound.wav");
SoundPlayer player1 = new SoundPlayer(path_sound);
player1.Play();