将绝对路径转换为相对路径 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13019402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting absolute path to relative path C#
提问by John Demetriou
Possible Duplicate:
Getting path relative to the current working directory?
可能的重复:
获取相对于当前工作目录的路径?
I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.
我有 C# 代码,其中包含从绝对路径到相对路径的一些图像,因此无论应用程序折叠位于何处,都可以找到图像。
For example the path in my code (and in my laptop for the image) is
例如,我的代码(以及我的笔记本电脑中的图像)中的路径是
C:/something/res/images/image1.jpeg
and I want the path in my code to be
我希望我的代码中的路径是
..../images/image1.jpeg
So it can run wherever the folder is put, whatever the name of the C:partition is etc.
所以它可以在文件夹所在的任何地方运行,无论C:分区的名称是什么等等。
I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.
我想在我的代码中有一个独立于应用程序文件夹位置的路径,或者它是否在另一个分区中,只要它与解决方案的其余部分在同一个文件夹中。
I have this code:
我有这个代码:
try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}
This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?
此代码仅在文件和文件夹位于该特定路径(这也是代码的位置)时才运行,我希望该路径是相对的,因此无论我放置整个文件夹(代码、文件等),程序仍将只要代码(在项目文件夹下)与文件夹图像在同一位置就可以工作......我该怎么办?
采纳答案by Blake
Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".
相对路径基于运行应用程序的二进制文件。默认情况下,您的二进制文件将在 /bin/debug.conf 中输出[directory of your .csproj]。因此,假设您想创建与 .csproj 相同级别的图像文件夹。然后您可以使用相对路径“../../images/someImage.jpg”访问您的图像。
To get a better feel for this, try out the following as a test:
为了更好地了解这一点,请尝试以下测试:
1) create a new visual studio sample project,
1)创建一个新的visual studio示例项目,
2) create an images folder at the same level as the .csproj
2) 创建一个与 .csproj 相同级别的图像文件夹
3) put some files in the images folder
3)把一些文件放在images文件夹中
4) put this sample code in your main method -
4)将此示例代码放在您的主要方法中 -
static void Main(string[] args)
{
Console.WriteLine(Directory.GetCurrentDirectory());
foreach (string s in Directory.EnumerateFiles("../../images/"))
{
Console.WriteLine(s);
}
Console.ReadLine(); // Just to keep the console from disappearing.
}
You should see the relative paths of all the files you placed in step (3).
您应该会看到您在步骤 (3) 中放置的所有文件的相对路径。
回答by viggity
see: Getting path relative to the current working directory?
请参阅:获取相对于当前工作目录的路径?
Uri uri1 = new Uri(@"c:\foo\bar\blop\blap");
Uri uri2 = new Uri(@"c:\foo\bar\");
string relativePath = uri2.MakeRelativeUri(uri1).ToString();
回答by Konrad Viltersten
Depending on the set up of your program, you might be able to simply use a relative path by skipping a part of the full path string. It's not braggable, so J. Skit might be up my shiny for it but I'm getting the impression that you simply want to make it work. Beauty being a later concern.
根据您的程序设置,您可以通过跳过完整路径字符串的一部分来简单地使用相对路径。这不值得吹嘘,所以 J. Skit 可能是我的闪光点,但我得到的印象是你只是想让它工作。美丽是后来的关注点。
String absolutePath = @"c:\beep\boop\HereWeStart\hopp.gif";
String relativePath = absolutePath.Substring(13);
You could then, if you need/wish, exchange the number 13 (which is an ugly and undesirable approach, still working, though) for a dynamically computed one. For instance (assuming that the directory "HereWeStart", where your relative path is starting, is the first occurrence of that string in absolutePath) you could go as follows.
然后,如果您需要/希望,您可以将数字 13(这是一种丑陋且不受欢迎的方法,但仍然有效)交换为动态计算的数字。例如(假设您的相对路径开始的目录“HereWeStart”是该字符串第一次出现在 中absolutePath)您可以按如下方式进行。
String absolutePath = @"c:\beep\boop\HereWeStart\hopp.gif";
int relativePathStartIndex = absolutePath.IndexOf("HereWeStart");
String relativePath = absolutePath.Substring(relativePathStartIndex);
Also, your question begs an other question. I'd like to know how you're obtaining the absolute path. Perhaps there's an even more clever way to avoid the hustle all together?
另外,你的问题引出了另一个问题。我想知道你是如何获得绝对路径的。也许有更聪明的方法可以避免一起喧嚣?
EDIT
编辑
You could also try the following approach. Forget the Directoryclass giving you an absolute path. Go for the relative path straight off. I'm assuming that all the files you're attempting to remove are in the same directory. If not, you'll need to add some more lines but we'll cross that bridge when we get there.
您也可以尝试以下方法。忘记Directory给你一个绝对路径的类。直接走相对路径。我假设您尝试删除的所有文件都在同一目录中。如果没有,您将需要添加更多线路,但我们到达那里后会越过那座桥。
Don't forget to mark an answer as green-checked (or explain what's missing or improvable still).
不要忘记将答案标记为绿色检查(或解释遗漏或仍可改进的内容)。
String
deletableTarget = @"\images\image1.jpeg",
hereWeAre = Environment.CurrentDirectory;
MessageBox.Show("The taget path is:\n" + hereWeAre + deletableTarget);
try
{ File.Delete(hereWeAre + deletableTarget); }
catch (Exception exception)
{ MessageBox.Show(exception.Message); }
Also, please note that I took the liberty of changing your exception handling. While yours isworking, it's a better style to rely on the built-in messaging system. That way you'll get more professionally looking error messages. Not that we ever get any errors at run-time, right? ;)
另外,请注意,我冒昧地更改了您的异常处理。当您的系统工作时,依靠内置消息传递系统是一种更好的方式。这样,您将获得看起来更专业的错误消息。并不是说我们在运行时会遇到任何错误,对吧?;)

