问题描述
以下用 C# 编写的程序在 Windows 中运行良好,但在 Linux(在 docker 容器内)中运行时,它无法正确转换路径。
DELETE
我应该使用什么确切的路径?我尝试了各种组合。
解决方法
在 Windows 中,您有“本地路径”,它以指代本地驱动器的字母开头,然后是网络路径,以双反斜杠开头,后跟某个域/IP,然后是目录共享(所有这些都可以映射到另一个字母,以便于访问)
要从 Linux 访问网络共享,您需要将共享挂载到 Linux 树的某个位置。
你可以在网上查看很多例子,这里是一个:Mounting and mapping shares between Windows and Linux with Samba
此外,生成的路径看起来与您在 Windows 中的路径完全不同,因此,您需要(以某种方式)知道您正在哪个 SO 下运行,并相应地配置您的路径。
,一些建议
- 检查软管环境并相应地操纵路径。
- 您可以使用
Path.Combine()
来制定路径。
此应用程序的示例如下
using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
try {
bool validLogin = ValidateUser("domain","username","password" );
if (validLogin)
{
var path = Path.Combine("\\\\10.123.123.123","folder$","subfolder");
string fullPath = Path.Combine(path,"file_name1");
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
path = path.Replace(@"\",@"/");
fullPath = fullPath.Replace(@"\",@"/");
}
string body = "Test File Contents";
if (!Directory.Exists(path))
{
Directory.CreateDirectory((path));
}
File.WriteAllText(fullPath,body);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + ex.Message);
}
}
public static bool ValidateUser(string domainName,string username,string password)
{
string userDn = $"{username}@{domainName}";
try
{
using (var connection = new LdapConnection {SecureSocketLayer = false})
{
connection.Connect(domainName,LdapConnection.DefaultPort);
connection.Bind(userDn,password);
if (connection.Bound)
return true;
}
}
catch (LdapException )
{
// Log exception
}
return false;
}
}