Relative Paths in Winforms - c#

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();

Related

Dealing with paths in MVC libraries

I have an MVC project and a class library just for saving and deleting images.
I have the path to those images stored in a variable as a relative path
Content\images\ that I reference inside the Save() and Delete() methods.
The save method works as I would think but the delete throws an error as it's relating the current path from the window directory.
// Works fine
File.WriteAllBytes(Path.Combine(Settings.ImagesPath, filename), binaryData);
// Error saying it cannot find the path in the C:\windows\system32\folder
File.Delete(Path.Combine(Settings.ImagesPath, filename));
I'd like to be able to switch between relative and absolute paths in my Settings.ImagesPath string but every SO article I've tried works for one scenario or the other. What's the best way to convert absolute or relative paths to some common way to deal with them?
You should use Server.MapPath method to generate the path to the location and use that in your Path.Combine method.
var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
System.IO.File.Delete(fullPath);
Server.MapPath method returns the physical file path that corresponds to the specified virtual path. In this case, Server.MapPath(Settings.ImagesPath) will return the physical file path to your Content\images\ which is inside your app root.
You should do the same when you save the file as well.
You can also check the existence of the file before attempting to delete it
var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
Server.MapPath expects a relative path. So if you have an absolute value in the Settings.ImagePath, You can use the Path.IsPathRooted method to determine if it is a virtual path or not
var p = Path.Combine(Path.IsPathRooted(Settings.ImagesPath)
? path : Server.MapPath(Settings.ImagesPath), name);
if (System.IO.File.Exists(p))
{
System.IO.File.Delete(p);
}
When you use the virutal path, make sure it start with ~.
Settings.ImagesPath = #"~\Contents\Pictures";

Error the relative path of resources folder auto change to absolute path in C#

The code below i use to read lines from file test.txt in my folder Resources of my project.
string[] test = File.ReadAllLines(#"Resources\test.txt");
The properties are already change to "Content" and "Copy Always".
When i run the program, somtimes the path auto change to the Absolute path as:
"C:\Users\Documents\Resources\test.txt
And the program error because cannot find the path.
You are using a relative path to the file, which relies on the CurrentDirectory being valid. This is either changing, or not being set to the desired directory when the program is executed. You can test this failure with this code:
string CurrentDirectory = Environment.CurrentDirectory;
Log.Trace($"CurrentDirectory = {CurrentDirectory}");
System.IO.File.ReadAllText(#"Resources\test.txt");
Environment.CurrentDirectory = #"C:\Tools";
// changing the current directory will now cause the next command to fail
System.IO.File.ReadAllText(#"Resources\test.txt");
You should not rely on the CurrentDirectory path being set correctly. Get the directory of the current running executable with something like this:
string ExePath = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)
.Directory.FullName;
string FullPath = System.IO.Path.Combine(ExePath, "Resources", "test.txt");
System.IO.File.ReadAllText(FullPath);
Yo could use
Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "Resources", "test.txt"
to get the path.
But to your problem: I think, the problem is the ReadAllLines, because it wants to convert the string to an absolute path. So the problem shouldn't exist anymore, if you localize the string, or even make somenthing like:
var path = "" + "Resources\\test.txt";
var test = File.ReadAllLines(path);
I couldn't test this though because I couldn't reproduce your problem.

Create a folder in Documents C# WPF

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()

How to get files from a directory with relative path "Directory.GetFiles(sPath) "

I have relative path of a directory like "..\work\FilesDirectory". How to get all files from this directory.
I am currently using the following line of code but it requiresw absolute path.
string []AllFiles = Directory.GetFiles(sPath);
You should you Path.Combine to construct absolute path or you can change Current Directory so relative path points to location you need.
// Building c:\my\home\work\FilesDirectory
var absolutePath = Path.Combine(#"c:\my\home\toys\", #"..\work\FilesDirectory" );
Note: you need to know what location the path is relative to. I.e. if it relative to executable use Assembly.GetEntryAssembly().Location as base path.
If relative path represents your Project Debug folder then you can use:
string relativePath = AppDomain.CurrentDomain.BaseDirectory & "work\FilesDirectory"
Or you can also use config file to save your path and use string.Join() but its better to use Path.Combine instead.
You could always use the Directory.GetCurrentDirectory and the Directory.GetParent methods.
DirectoryInfo parentDirectoryInfo = System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory());
string []AllFiles = Directory.GetFiles(parentDirectoryInfo.FullName);
Hope I helped!

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

Categories