Evyatar
Evyatar

Reputation: 1157

Remove file:// prefix c#

I have the follow:

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

Now file is:

file:\C:\test\Debugbla.xml

How can i remove the "file:\" prefix?

Thanks

Upvotes: 5

Views: 2481

Answers (6)

maisels
maisels

Reputation: 19

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

}

Upvotes: 0

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

Uri class is the way to manipulate Uri. While string.Replace is an option it is better to use tools explicitly designed for particular case which also take care of handling escaping rules where necessary.

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

file = new Uri(file).AbsolutePath; 

UPDATE:

More robust implementation eliminating string.Concat to handle other cases including fragments in the codebase url.

var codebase = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

var file = new Uri(codebase, "bla.xml").AbsolutePath;

Upvotes: 14

Awaa
Awaa

Reputation: 178

If you need to access the path you can use GetExecuting Assembly and convert it into an Uri:

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

Or using Location:

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

If you just need the directory and the entry point, the following will work:

var dir = AppDomain.CurrentDomain.BaseDirectory;

Upvotes: 0

SLaks
SLaks

Reputation: 887967

Use the Assembly.Location property instead, which returns a normal filepath.

Also, use Path.Join().

Upvotes: 2

phishfordead
phishfordead

Reputation: 387

You could replace the file:\ part of the path like so.

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

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

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

You can replace it with empty string.

Upvotes: 0

Related Questions