views:

130

answers:

6
string path = Path.GetDirectoryName(
                     Assembly.GetAssembly(typeof(MyClass)).CodeBase);

output:

file:\d:\learning\cs\test\test.xml

What's the best way to return only d:\learning\cs\test\test.xml

file:\\ will throw exception when I call doc.Save(returnPath) ,however doc.Load(returnPath); works well. Thank you.

+2  A: 

My first approach would be like this...

path.Replace("file://", "");
The King
+4  A: 
string path = Path.GetDirectoryName(  
                 Assembly.GetAssembly(typeof(MyClass)).CodeBase);  
path = path.Replace("file://", string.Empty);
Ardman
+1  A: 

use the substring string method to grab the file name after file:\

VoodooChild
+4  A: 
string path = new Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase).LocalPath;
Matthew Flaschen
+3  A: 
  System.Uri uri = new System.Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
  string path = Path.GetDirectoryName(uri.LocalPath);
Moe Sisko
+2  A: 

If you want the directory of the assembly of that class, you could use the Assembly.Location property:

string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).Location);

This isn't exactly the same as the CodeBase property, though. The Location is the "path or UNC location of the loaded file that contains the manifest" whereas the CodeBase is the " location of the assembly as specified originally, for example, in an AssemblyName object".

Chris Schmich
@Chris,Thanks for your Simple but perfect solution. @all, Thank you.
Nano HE