Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i remove the file name from a path directory string?

Tags:

c#

.net

winforms

This is the line:

string f = Path.GetFullPath("c:\\t.txt").Replace(":", "").Replace("\\", "/");

I tried something with: string t = f.LastIndexOf("/"); but that's not working. f now is: c/t.txt I need that f will be only c/ And if the directory with the file name was: c:\subdir\sub\t.txt So in the end f should be: c/subdir/sub without the t.txt in the end.

I tried this now:

The problem is that when i'm doing:

f.TargetFolder = Path.GetDirectoryName(txf);
f.TargetFolder = Path.GetFullPath(txf).Replace(":", "").Replace("\\", "/");

the second line with the Replace leave me with C/test.txt I tried to make only replace for the string it self without GetFullPath only fro the txf but same result in TargetFolder i have c/test.txt and i need to be with only c/ The line with the Replace is not good it's not giving me the result i need.

like image 330
Jorge Hyyest Avatar asked Dec 15 '14 17:12

Jorge Hyyest


1 Answers

Use Path.GetDirectoryName to get the part of a file path that represents the directory that contains the file. For example:

Path.GetDirectoryName("C:\\path\\to\\file.txt"); // returns C:\path\to

More examples:

INPUT                              OUTPUT
---------------------------------  ------------------------
C:\path\to\file.txt                C:\path\to
C:\path\to\                        C:\path\to
C:\path\to                         C:\path
C:\path\                           C:\path
C:\path                            C:\
C:\                                (null)
C:                                 (null)
\path\to\file.txt                  \path\to
path\to\file.txt                   path\to
\\server\share\path\to\file.txt    \\server\share\path\to
\\server\share                     (null)
\\server                           (null)

(null) above indicates that the return value is the null value, not a string.

like image 54
Mårten Wikström Avatar answered Sep 30 '22 16:09

Mårten Wikström