2017-09-10 30 views
3
String machineName = System.Environment.MachineName; 
String filePath = @"E:\folder1\folder2\file1"; 
int a = filePath.IndexOf(System.IO.Path.DirectorySeparatorChar); 
filePath = filePath.Substring(filePath.IndexOf(System.IO.Path.DirectorySeparatorChar) +1); 
String networdPath = System.IO.Path.Combine(string.Concat(System.IO.Path.DirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar), machineName, filePath); 
Console.WriteLine(networdPath); 

私はString.ConcatPath.Combineを使って上記のコードを書いて、ネットワークパスを取得しました。しかし、これは単なる回避策であり、具体的な解決策ではなく、失敗する可能性があります。 ネットワークパスを取得するための具体的なソリューションはありますか?PCのローカルファイルパスをネットワーク相対パスまたはUNCパスに変換する方法は?

+0

https://stackoverflow.com/questions/2067075/how-do-i-determine-a-mapped-drives-actual-path –

答えて

1

E:\folder1ローカルパスが\\mypc\folder1と共有されていると仮定していますが、これは一般的には真実ではありません。したがって、あなたがしたいことを行う一般的な方法は疑わしいです。

達成しようとしていることを実装するには正しい道のりです。 System.IO.Pathから詳細なヘルプを得ることができます。入力に経路の異なる種類に応じて返された値のためMSDNPath.GetPathRoot参照

string GetNetworkPath(string path) 
{ 
    string root = Path.GetPathRoot(path); 

    // validate input, in your case you are expecting a path starting with a root of type "E:\" 
    // see Path.GetPathRoot on MSDN for returned values 
    if (string.IsNullOrWhiteSpace(root) || !root.Contains(":")) 
    { 
     // handle invalid input the way you prefer 
     // I would throw! 
     throw new ApplicationException("be gentle, pass to this function the expected kind of path!"); 
    } 
    path = path.Remove(0, root.Length); 
    return Path.Combine(@"\\myPc", path); 
} 
+0

ニースですが、私たちのソリューションはMicrosoft Windowsでのみ動作します.Mac OSネットワークパスのパターンは、Windowsのパターンとは異なる場合があり、当社のソリューションはそこでは機能しません。それで、すべての可能なOSで動作するMicrosoftが提供する具体的なソリューションがあります。 – rrc1709

関連する問題