Correct filepath to read from file - c#

I want to read from a file. But i do not how to alter to the correct filepath.
I just want to read from a file called Level.txt. If I do; string path = "Level.txt".
The program tries to search it from; C:\...\ProjIV\ProjIV\bin\x86\debug\Level.txt.
When I want the damn thing in: C:\...\ProjIV\ProjIV\ProjIVContent\Level.txt.
Skip the second question. As someone else said, one question at the time. Also; solved.

If you just provide a path like that, your program will search in the running (working) directory that it is executing in. You can provide an explicit path:
C:\<whatever you need here>\ProjIV\ProjIV\ProjIVContent\Level.txt
Or a relative path:
..\..\..\..\ProjIVContent\Level.txt
That's pretty ugly though, I'd stick with the first one. Or move Level.txt into your working directory.

Related

Differences between "Path" and "Directory" classes and means

I don't understand the difference between path and directory. Could someone explain to me with examples?
I'm trying to understand how to different classes of system.IO namespace works. But in logicaly I didn't get the mean what is "Path" , what is "Directory". Aren't they both the same thing? Why they divided these 2 thing into two different classes?
Directory is more of a confirmation or assessment of. For example. Does a directory exist providing a string representing the path you are interested in. Create a directory, again, provided a string representing the path.
var myStrPath = #"C:\Users\Public\SomePath\";
if( ! Directory.Exists( myStrPath ))
Directory.Create( myStrPath );
You can also enumerate a given folder looking for more, or cycling through them.
var df = Directory.GetDirectories(#"C:\");
foreach (var oneFolder in df)
MessageBox.Show(oneFolder.ToString());
But you can also use Directory based on RELATIVE Path. For example, where your program is running from, you could do
if( Directory.Exists( "someSubFolderFromWhereRunning" ))
and not worry about fully qualified path.
Path allows you to get or manipulate path/file information, such as a relative path above and you want to know its FULL path even though you dont know where your program is running from. This might be good to look for an expected startup check file in the relative directory the app is running from, or writing files out to same working folder.
You can also get the list of bad characters that are not allowed in a path so you can validate against them in some string.
For each of them, take a look at the "." reference after you do something like
var what = System.IO.Directory. [and look at the intellisense]
var what2 = System.IO.Path. [intellisense]
And look at the context. It should make more sense to you seeing it with better context.
A Directory is a disk file that contains reference information to other files. or in simple words, it is a folder.
A Path is just a string wrapped in a Path Class in C# which facilitates us with many different conventions depending on the operation system.

StringBuilder remove characters until certain character is reached

I am developing a program that functions similar to the MS-DOS command "cd". The user types "cd.." into the program's prompt and then, using Stringbuilder, remove the characters representing the user's current directory. It would function like this:
Prompt> cd..
with a Stringbuilder instance declared in the code file:
Stringbuilder builder = new Stringbuilder(#"E:\Folder");
After the user types "cd.." and hits Enter, the program would remove the directory at the end of the Stringbuilder value, with the end result like this:
Stringbuilder builder = new Stringbuilder(#"E:\");
I am not sure how I can do this, or if it is even possible to do. I thought I could try builder.Length - Directory.Length to get the length of the directory name, and then use builder.Remove(int StartIndex, int length), but I don't know how that could be implemented.
Another thing I could possibly use is using builder.ToString() and split it, using the backslash as the seperator.
Any suggestions?
You could use Path.GetDirectoryName, but it's kind of dumb. It just does string manipulation with no idea what the file system actually looks like. For example, if you do Path.GetDirectoryName(#"E:\Folder\") it will return "E:\Folder", because there was a slash at the end of the string you gave it. Or you could feed it a folder that doesn't even exist, and it'll still give you an answer.
I can suggest another way to do this: keep a DirectoryInfo object for the current working directory. For example:
var curDirectory = new DirectoryInfo(#"E:\Folder");
When you need to display it, use curDirecotry.FullName, which will return the full path, like "E:\Folder". Then when you need to go up a directory, it's one line with no string manipulation:
curDirectory = curDirectory.Parent;
Although you do have to check it for null since, if you are already at the root of the drive, Parent will be null.
DirectoryInfo actually looks at the file system so you can be sure that it's always valid. Plus, you can use it for seeing the contents of the folder too, which I'm sure you will want to do.

Navigating back and forward at once in path C#

I have to come back 5 folders in path then I need to enter 3 folders further and check if file exist.
Lets imagine two paths:
1) C:\a\b\c\d\e\f\g\
2) C:\a\2\3\4\5\test.xml
Then my program right now is on the first path.
I need to check if file test.xml (on the second path) exists.
For that I know method File.Exists(path), however I have problems with path.
I am able to come back until folder a and check if the file is there.
For example to check if the file on the path exists:
3) C:\a\test2.xml
I may use:
File.Exists(#".\.\.\.\.\.\" + #"test2.xml");
But nevertheless my attempts to navigate to second path ( 2) ) and check if this file exists I can not to that. May anyone help me with that ? Thanks in advance. Regards.
. refers to the current directory
.. refers to the directory one level above the current
In your example:
..\..\..\..\..\..\2\3\4\5\test.xml
This moves up to the a directory then traverses down to 5 where your file resides.
Something that might be helpful to test your path and ensure you are where you think you are is this:
string currentPath = Path.GetFullPath(relativePath);
And then check the value of currentPath, if it winds up somewhere you didn't expect you can debug your path traversal rather than your code.
You just need to use .. to signify a parent directory.
Try:
File.Exists(#"..\..\..\..\..\..\" + #"test2.xml");

Appending Text to a file path

This is probably a simple question, I'm writing a WinForms C# application in VS 2012. I was wondering if there a way to add an extension such as .csv to some writing in a textbox. Say the user wrote in C:\Users\Desktop\filename but left out the .csv part of the path. Is there any way to add the .csv after an execute button is clicked?
Any help would be much appreciated.
You can use Path.ChangeExtension.
// Nota bene: Path.ChangeExtension does not change textBox1.Text directly (or any
// argument given), you MUST use the result if you care about it.
string newPath = Path.ChangeExtension(textBox1.Text, "csv");
The period is optional, and the filename component need not include an extension.
As a future reference, if you can think of something you need to do with a path to a file or a directory...it exists in System.IO.Path. Rare for there not to be support for a common task in that class.
If you do not want to change a valid extension in the string, you could do it like this instead:
// first test for an extension
if(!Path.HasExtension(textBox1.Text.Trim()))
{
// then add on '.csv' if one does not exist
string path = Path.ChangeExtension(textBox1.Text.Trim(), ".csv");
// ... use path ...
}

How do I find the parent directory in C#?

I use this code for finding the debug directory
public string str_directory = Environment.CurrentDirectory.ToString();
"C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug"
How can I find the parent folder as shown below?
"C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj"
You can use System.IO.Directory.GetParent() to retrieve the parent directory of a given directory.
string parent = System.IO.Directory.GetParent(str_directory).FullName;
See BOL
If you append ..\.. to your existing path, the operating system will correctly browse the grand-parent folder.
That should do the job:
System.IO.Path.Combine("C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug", #"..\..");
If you browse that path, you will browse the grand-parent directory.
Edit: The normalization covered in this answer only happens when the path is used to access the file system, but not on the string itself. By contrast, this answer achieves the result and normalization purely using path strings, without using the file system at all.
I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.
Path.Combine makes sure you never go wrong with slashes.
.. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.
Some basic .. behavior:
If there is a file name, .. will chop that off:
Path.Combine(#"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\
If the path is a directory, .. will move up a level:
Path.Combine(#"D:\Grandparent\Parent\", "..") => D:\Grandparent\
..\.. follows the same rules, twice in a row:
Path.Combine(#"D:\Grandparent\Parent\Child.txt", #"..\..") => D:\Grandparent\
Path.Combine(#"D:\Grandparent\Parent\", #"..\..") => D:\
And this has the exact same effect:
Path.Combine(#"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\
Path.Combine(#"D:\Grandparent\Parent\", "..", "..") => D:\
To get a 'grandparent' directory, call Directory.GetParent() twice:
var gparent = Directory.GetParent(Directory.GetParent(str_directory).ToString());
Directory.GetParent is probably a better answer, but for completeness there's a different method that takes string and returns string: Path.GetDirectoryName.
string parent = System.IO.Path.GetDirectoryName(str_directory);
Like this:
System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
string parentDirectory = myDirectory.Parent.FullName;
Good luck!
No one has provided a solution that would work cross-form. I know it wasn't specifically asked but I am working in a linux environment where most of the solutions (as at the time I post this) would provide an error.
Hardcoding path separators (as well as other things) will give an error in anything but Windows systems.
In my original solution I used:
char filesep = Path.DirectorySeparatorChar;
string datapath = $"..{filesep}..{filesep}";
However after seeing some of the answers here I adjusted it to be:
string datapath = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).FullName).FullName;
You might want to look into the DirectoryInfo.Parent property.
IO.Path.GetFullPath(#"..\..")
If you clear the "bin\Debug\" in the Project properties -> Build -> Output path, then you can just use AppDomain.CurrentDomain.BaseDirectory
Since nothing else I have found helps to solve this in a truly normalized way, here is another answer.
Note that some answers to similar questions try to use the Uri type, but that struggles with trailing slashes vs. no trailing slashes too.
My other answer on this page works for operations that put the file system to work, but if we want to have the resolved path right now (such as for comparison reasons), without going through the file system, C:/Temp/.. and C:/ would be considered different. Without going through the file system, navigating in that manner does not provide us with a normalized, properly comparable path.
What can we do?
We will build on the following discovery:
Path.GetDirectoryName(path + "/") ?? "" will reliably give us a directory path without a trailing slash.
Adding a slash (as string, not as char) will treat a null path the same as it treats "".
GetDirectoryName will refrain from discarding the last path component thanks to the added slash.
GetDirectoryName will normalize slashes and navigational dots.
This includes the removal of any trailing slashes.
This includes collapsing .. by navigating up.
GetDirectoryName will return null for an empty path, which we coalesce to "".
How do we use this?
First, normalize the input path:
dirPath = Path.GetDirectoryName(dirPath + "/") ?? ""; // To handle nulls, we append "/" rather than '/'
Then, we can get the parent directory, and we can repeat this operation any number of times to navigate further up:
// This is reliable if path results from this or the previous operation
path = Path.GetDirectoryName(path);
Note that we have never touched the file system. No part of the path needs to exist, as it would if we had used DirectoryInfo.
To avoid issues with trailing \, call it this way:
string ParentFolder = Directory.GetParent( folder.Trim('\\')).FullName;
To get your solution
try this
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
This is the most common way -- it really depends on what you are doing exactly:
(To explain, the example below will remove the last 10 characters which is what you asked for, however if there are some business rules that are driving your need to find a specific location you should use those to retrieve the directory location, not find the location of something else and modify it.)
// remove last 10 characters from a string
str_directory = str_directory.Substring(0,str_directory.Length-10);
You shouldn't try to do that. Environment.CurrentDirectory gives you the path of the executable directory. This is consistent regardless of where the .exe file is. You shouldn't try to access a file that is assumed to be in a backwards relative location
I would suggest you move whatever resource you want to access into a local location. Of a system directory (such as AppData)
In my case I am using .NET 6. When I use:
public string str_directory = Environment.CurrentDirectory.ToString();
returns C:\Projects\MyTestProject\bin\Debug\net6.0
In order to reach C:\Projects\MyTestProject I am using the following:
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent
You can chain Parent to Directory.GetParent(Environment.CurrentDirectory) in order to reach the directory you want.
Final version:
public string str_directory = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.ToString();

Categories