Is there a method to manage relative paths in C#? [duplicate] - c#

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

Related

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

How to get image files in c# using relative path?

I've checked this thread How to get files in a relative path in C#, the directory is in IDE, which is not correct for me. I have a website application, needs to get image files from the same level folder img. I can use following code to get them:
DirectoryInfo path=new DirectoryInfo(#"c:\WebsiteSolution\wwwroot\Chat\img");
FileInfo[] images = path.GetFiles("*");
But I want to use something like .\img to replace the parameter in the first line code, is that possible?
Call the Server.MapPath utility to get the relative path.
DirectoryInfo path = Server.MapPath("~\Chat\img");
For ASP.Net use MapPath - http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx.
Also if you just need to construct path for rendering a page just /Chat/img/My.gif is enough.
You need to find an anchor - something like Application.ExecutablePath - and then use that anchor with Path.Combine() to reach your image directory.
If your Application.ExecutablePath were: #"c:\WebSiteSolution\wwwroot\chat\code", then you could use string imgPath = Path.Combine(Application.ExecutablePath, #"..\img");
If you have a hard time finding a good anchor, there's a bunch to consider. You can get the path of the executing assembly via Assembly.GetExecutingAssembly().Location

Relative path to absolute path in C#?

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

How can I save an Image to the File System?

I'm trying to create a folder on the directory where the .exe file is and save a picture in that folder.
Right now that folder doesn't exist so I'd like to be created. Here's the code I have:
public void SavePictureToFileSystem(string path, Image picture)
{
string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
picture.Save(pictureFolderPath + "1.jpg");
}
The Image isn't being saved to the pictureFolderPath but to the path variable. What do I need to accomplish this?
Thanks for the help! This is what I ended up with:
public void SavePictureToFileSystem(string path, Image picture)
{
var pictureFolderPath = Path.Combine(path, ConfigurationManager.AppSettings["picturesFolderPath"].ToString());
if (!Directory.Exists(pictureFolderPath))
{
Directory.CreateDirectory(pictureFolderPath);
}
picture.Save(Path.Combine(pictureFolderPath, "1.jpg"));
}
I suspect your problem is that ConfigurationManager.AppSettings["picturesFolderPath"].ToString() returns a folder-path that is empty or, more likely, does not end with a trailing back-slash. This would mean that the final constructed path would end up looking like c:\dir1.jpg rather than c:\dir\1.jpg, which is what I think you really want.
In any case, it's much better to rely onPath.Combinethan to try to deal with the combining logic yourself. It deals with precisely these sorts of corner-cases, plus, as a bonus, it's platform-independent.
var appFolderPath = ConfigurationManager.AppSettings["picturesFolderPath"]
.ToString();
// This part, I copied pretty much verbatim from your sample, expect
// using Path.Combine. The logic does seem a little suspect though..
// Does appFolder path really represent a subdirectory name?
var pictureFolderPath = Path.Combine(path, appFolderPath);
// Create folder if it doesn't exist
Directory.Create(pictureFolderPath);
// Final image path also constructed with Path.Combine
var imagePath = Path.Combine(pictureFolderPath, "1.jpg")
picture.Save(imagePath);
I suspect ConfigurationManager.AppSettings["picturesFolderPath"].ToString() might be empty, so the pictureFolderPath variable is only being set to the path value. Make sure it is set properly and the value is being returned. Put a breakpoint on that line and check it in the Watch/Immediate windows.
You could try to create the directory first:
Directory.CreateDirectory(pictureFolderPath);

How to get a part from the full path in C#?

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.

Categories