May 11, 2005

System.Uri Class.

Using System.Uri with a local file
Uri uri = new Uri(@"c:\somefile.dat");
uri.LocalPath  => returns 'c:\somefile.dat'
uri.ToString() => returns 'file:///c:/somefile.dat'
C# Uri Class - With lots of samples using console output to show their effects.

Always use IsWellFormedUriString before constructing an instance to ensure that the string being used is valid:
string GetUriContents(string uriString)
{
 string contents = "";
 if (!string.IsNullOrWhiteSpace(uriString) &&
         Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
 {
  Uri uri = new Uri(uriString);
  if (uri.IsAbsoluteUri || uri.IsUnc)
  {
   UrlLoader urlLoader = new UrlLoader();
   contents = urlLoader.TryGetUrlContents(uri.AbsoluteUri);
   if (contents.Length > 0)
    DoSomething();
  } 
  else if (uri.IsFile)
  {
   contents = File.ReadAllText(uri.LocalPath);
  }
 }
 return contents;
}

No comments: