删除 file:// 前缀 c#

本文关键字:前缀 file 删除 | 更新日期: 2023-09-27 18:17:57

我有以下内容:

string file = string.Concat(
                 System.IO.Path.GetDirectoryName(
                    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
                 ), 
              "bla.xml");

现在文件是:

file:'C:'test'Debugbla.xml

如何删除"文件:''"前缀?

谢谢

删除 file:// 前缀 c#

Uri

类是操作 Uri 的方法。虽然string.Replace是一种选择,但最好使用为特定情况明确设计的工具,这些工具还负责在必要时处理转义规则。

string file = string.Concat(System.IO.Path.GetDirectoryName(
     System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "bla.xml");
file = new Uri(file).AbsolutePath; 

更新:

更健壮的实现消除了处理其他情况(包括代码库 URL 中的片段(string.Concat

var codebase = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
var file = new Uri(codebase, "bla.xml").AbsolutePath;

请改用 Assembly.Location 属性,该属性返回正常的文件路径。

另外,请使用 Path.Join() .

file = file.Replace(@"file:'", "");

您可以将其替换为空字符串。

你可以替换文件:''路径的一部分就是这样。

string file = string.Concat(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "bla.xml");
file = file.Replace(@"file:'","");

如果需要访问路径,可以使用 GetExecute Assembly 并将其转换为 Uri:

string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);

或使用位置:

string fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;

如果您只需要目录和入口点,则以下内容将起作用:

var dir = AppDomain.CurrentDomain.BaseDirectory;
using System.IO;
var folderPath = @"C:''Users''user''Downloads''Music'";

foreach (string file in Directory.GetFiles(folderPath, "*.*"))
{
    var newFile = file.Replace("[SPOTIFY-DOWNLOADER.COM]", "");
    File.Move(file, newFile);
}