在C#中最简单的方法是如何找出应用程序是否从网络驱动器运行?

19

我希望以编程方式找出我的应用程序是否从网络驱动器运行。最简单的方法是什么?它应该支持UNC路径(\\127.0.0.1\d$)和映射的网络驱动器(Z:)。

6个回答

23

这是针对映射驱动器的情况。你可以使用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)));    }

4
if (new DriveInfo(Application.StartupPath).DriveType == DriveType.Network)
{    
    // here   
}

2

我重新排列了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 {}
}

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

1
如果使用UNC路径,那么很简单 - 检查UNC中的主机名并测试它是否为localhost(127.0.0.1、::1、主机名、主机名.domain.local、工作站的IP地址)。
如果路径不是UNC - 从路径中提取驱动器号并测试DriveInfo类的类型。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接