I have a full path as given below.
C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd
How can the DTDs "part" to be fetched from this whole part?
Desired output:
C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs
Can I use String's methods for this?
If yes, then how to fetch it?
Use System.IO.Path.GetDirectoryName() for the entire path, or new DirectoryInfo(path).Parent.Name for just the name of that one folder.
There is no directory named "DTDs" in the path you posted. IT looks like there's a file named "DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd", but the periods (.) in that path are not valid directory separator characters. Did you mean "DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd"?
If that's the case, given that entire new path, you want something like this to return a list of files in the DTDs folder:
string path = #"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd";
string[] files = new DirectoryInfo(path).Parent.GetFiles();
in properties window i choose Build Type as Embedded resource.
And now we finally get to it. When you choose "Embedded Resource", the item is bundled into your executable program file. There is no direct path anymore. Instead, set your Build Type to "Content" and set "Copy to Output Directory" to "Copy Always" or "Copy if Newer".
Calling
System.IO.Path.GetFileName
with the full directory path returns the last part of the path which is a directory name. GetDirectoryName returns the whole path of parent directory which is unwanted.
If you have a file name and you just want the name of the parent directory:
var directoryFullPath = Path.GetDirectoryName(#"C:\DTDs\mydtd.dtd"); // C:\DTDs
var directoryName = Path.GetFileName(directoryFullPath); // DTDs
You can also use Directory to get the directory from the full file path:
Directory.GetParent(path).FullName
Edit: Please read the OP’s question and all of her comments carefully before downvotiong this. The OP’s title question isn’t EXACTLY what she wanted. My answer gave her what she needed to solve her problem. Which is why she voted it the answer. Yes, Joel’s answer is correct if specifically answering the title question. But after reading her comments, you’ll see that not exactly what she was looking for. Thanks.
Use this ...
string strFullPath = #"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd";
string strDirName;
int intLocation, intLength;
intLength = strFullPath.Length;
intLocation = strFullPath.IndexOf("DTDs");
strDirName = strFullPath.Substring(0, intLocation);
textBox2.Text = strDirName;
System.IO.Path.GetFileName( System.IO.Path.GetDirectoryName( fullPath ) )
That will return just the name of the folder containing the file.
For
C:\windows\system32\user32.dll
this will return
system32
I'm inferring that that's what you want.
Use:
string dirName = new DirectoryInfo(fullPath).name;
You can use:
System.IO.Path.GetDirectoryName(path);
You can use Path ...
Path.GetDirectoryName(myStr);
Use the FileInfo object...
FileInfo info = new FileInfo(#"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd");
string directoryName = info.Directory.FullName;
The file doesn't even have to really exist.
Don't use string manipulation directly. Instead use GetDirectoryName of the Path class:
System.IO.Path.GetDirectoryName(myPath);
Path.GetDirectory on the path you have specified returns:
"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug"
Try it yourself:
var path = Path.GetDirectoryName(#"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd");
Your question is a little strange though- there is no directory called DTDs.
Related
I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx
Consider the two paths, one in a solution and the other in IIS:
Solution Path:
C:\Users\userid\Desktop\File\Solution\RootName\ Folder1 \Folder1a\the.aspx
IIS path
C:\inetpub\wwwroot\RootName\webApplication\ Folder1 \Folder1a\the.aspx
Is there a way using Directory or Server or anything at all to get the FIRST folder name after the Parent Directory?
ie in the given above, Folder1 is the first folder after the parent folder.
I can get the opposite, which is the containing folder name from a filepath (in this example, Folder1a) and I can iterate it to get to the answer :
Path.GetFileName(Path.GetDirectoryName(file));
But the problem is, folders can be nested at any amount: (folder1a\folder1a1\folder1a1a...)
How can I get the first folder name after the Parent Directory given a file path?
as an aside,
If there is no foldername (ex. Folder1 does not exist) the answer should output "" (empty)
Use .. to go to previous directory, example:
C:\test\..\
is equivalent to:
C:\
Use Directory.GetDirectories to find sub Directories. It has an overload where you can pass search patterns as well:
string[] GetDirectories(string path, string searchPattern)
searchPattern
Type: System.String
The search string to match against the names of subdirectories in path.
This parameter can contain a combination of valid literal and
wildcard characters (see Remarks), but doesn't support regular
expressions.
Try this:
string filename = string.Format("{0}{1}", System.AppDomain.CurrentDomain.BaseDirectory, #"Folder1\Folder1a\the.aspx");
Below is what I have tried that works.
Since I simply needed to output the first page after the word, I iterated Path.GetDirectoryName and Path.GetFileName until I could match the root folder.
Ex:
baseFoldr = "";
var curFile = Path.GetDirectoryName(file);
string curName = Path.GetFileName(curFile);
while (curName.ToLower() != "RootName")
{
curFile = Path.GetDirectoryName(curFile);
baseFoldr = curName;
curName = Path.GetFileName(curFile);
}
return baseFoldr;
I still believe there could be a better answer, though
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
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 have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx