2011-12-26 27 views

回答

2

这是我目前这样做的方法,但感觉应该有一个更好的办法。

private bool IsRunningFromNetworkDrive() 
    { 
     var dir = AppDomain.CurrentDomain.BaseDirectory; 
     var driveLetter = dir.First(); 
     if (!Char.IsLetter(driveLetter)) 
      return true; 
     if (new DriveInfo(driveLetter.ToString()).DriveType == DriveType.Network) 
      return true; 
     return false; 
    } 
18

这是映射驱动器的情况。您可以使用DriveInfo类来确定驱动器a是否是网络驱动器。

DriveInfo info = new DriveInfo("Z"); 
if (info.DriveType == DriveType.Network) 
{ 
    // Running from network 
} 

完整的方法和示例代码。

public static bool IsRunningFromNetwork(string rootPath) 
{ 
    try 
    { 
     System.IO.DriveInfo info = new DriveInfo(rootPath); 
     if (info.DriveType == DriveType.Network) 
     { 
      return true; 
     } 
     return false; 
    } 
    catch 
    { 
     try 
     { 
      Uri uri = new Uri(rootPath); 
      return uri.IsUnc; 
     } 
     catch 
     { 
      return false; 
     } 
    } 
} 

static void Main(string[] args) 
{ 
    Console.WriteLine(IsRunningFromNetwork(System.IO.Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory))); } 
1

在使用UNC路径情况下,静静简单 - 检查UNC主机名和测试,这是本地主机(127.0.0.1,:: 1,主机名,hostname.domain.local,工作站的IP位址) 或不。

如果路径是不UNC - 提取路径中的驱动器号和测试DriveInfo类其类型

4
if (new DriveInfo(Application.StartupPath).DriveType == DriveType.Network) 
{  
    // here 
} 
0
DriveInfo m = DriveInfo.GetDrives().Where(p => p.DriveType == DriveType.Network).FirstOrDefault(); 
if (m != null) 
{ 
    //do stuff 
} 
else 
{ 
    //do stuff 
} 
0

我重新安排dotnetstep的解决方案,这在我看来是更好,因为它在一个有效的路径传递避免了异常,如果有是传递一个错误的道路,它抛出一个异常,这不允许做出真假假设。

//---------------------------------------------------------------------------------------------------- 
/// <summary>Gets a boolean indicating whether the specified path is a local path or a network path.</summary> 
/// <param name="path">Path to check</param> 
/// <returns>Returns a boolean indicating whether the specified path is a local path or a network path.</returns> 
public static Boolean IsNetworkPath(String path) { 
    Uri uri = new Uri(path); 
    if (uri.IsUnc) { 
    return true; 
    } 
    DriveInfo info = new DriveInfo(path); 
    if (info.DriveType == DriveType.Network) { 
    return true; 
    } 
    return false; 
} 

测试:

//---------------------------------------------------------------------------------------------------- 
/// <summary>A test for IsNetworkPath</summary> 
[TestMethod()] 
public void IsNetworkPathTest() { 
    String s1 = @"\\Test"; // unc 
    String s2 = @"C:\Program Files"; // local 
    String s3 = @"S:\"; // mapped 
    String s4 = "ljöasdf"; // invalid 

    Assert.IsTrue(RPath.IsNetworkPath(s1)); 
    Assert.IsFalse(RPath.IsNetworkPath(s2)); 
    Assert.IsTrue(RPath.IsNetworkPath(s3)); 
    try { 
    RPath.IsNetworkPath(s4); 
    Assert.Fail(); 
    } 
    catch {} 
} 
相关问题