C# 修剪应用程序路径

发布于 2024-09-30 17:36:43 字数 295 浏览 6 评论 0原文

我有这个应用程序路径:

C:\Documents and Settings\david\My Documents\app\

和文件路径:

C:\Documents and Settings\david\My Documents\app\stuff\file.txt

如何从文件路径中修剪应用程序路径,使其变为 stuff\file.txt?原因是我正在使用的命令行工具之一不支持文件路径中的空格。

I have this application path:

C:\Documents and Settings\david\My Documents\app\

And a file path:

C:\Documents and Settings\david\My Documents\app\stuff\file.txt

How can I trim the application path from the file path so it becomes stuff\file.txt? Reason being one of the command line tools I'm using doesn't support spaces in the file path.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不再让梦枯萎 2024-10-07 17:36:43

试试这个:

Uri path = new Uri(@"C:\Documents and Settings\david\My Documents\app\stuff\file.txt");
Uri workingDirectory = new Uri(Directory.GetCurrentDirectory());
string relativePath = workingDirectory.MakeRelativeUri(path).ToString();

相关文档:

Try this:

Uri path = new Uri(@"C:\Documents and Settings\david\My Documents\app\stuff\file.txt");
Uri workingDirectory = new Uri(Directory.GetCurrentDirectory());
string relativePath = workingDirectory.MakeRelativeUri(path).ToString();

Related documentation:

凝望流年 2024-10-07 17:36:43

我不知道您使用的是哪个命令工具,但是如果我们将字符串/路径括在引号中,例如

“C:\ Documents and Settings \ david \ My Documents \ app \ stuff \ file.txt”,它们通常会起作用

i don't know which command tool you are using, but normally they work if we enclosed the string/ path in quotation marks like this

"C:\Documents and Settings\david\My Documents\app\stuff\file.txt"

翻身的咸鱼 2024-10-07 17:36:43

不知道为什么普通字符串替换不起作用:

string filePath = @"C:\Documents and Settings\david\My Documents\app\stuff\file.txt";
string appPath = @"C:\Documents and Settings\david\My Documents\app\";
string trimmed = filePath.Replace(appPath, "");

但是,如果您只是将完整路径括在引号中(),大多数命令行工具都可以使用空格:

string escapedPath = @"""C:\Documents and Settings\david\My Documents\app\stuff\file.txt""";

Not sure why normal string replace won't do:

string filePath = @"C:\Documents and Settings\david\My Documents\app\stuff\file.txt";
string appPath = @"C:\Documents and Settings\david\My Documents\app\";
string trimmed = filePath.Replace(appPath, "");

However, if you simply enclose the full path in quotes ("), most command line tools will be fine with spaces:

string escapedPath = @"""C:\Documents and Settings\david\My Documents\app\stuff\file.txt""";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文