将 VBScript 转换为 C#

Convert a VBScript to C#

谁能帮我把这个脚本转换成 C# 我仍然是一个初学者,正在学习 C#。该脚本使用 OpenCurrentDatabase 打开(并保持打开)一个 Access .mdb 文件,我必须按原样使用此方法和代码,但转换为 C#,非常感谢任何帮助。

我正在使用记事本编辑 cs 文件并csc.exe编译它(我没有任何其他 C# 工具)。

dim fso    
Set fso = CreateObject("Scripting.FileSystemObject")

dim filePath
filePath = fso.GetParentFolderName(WScript.ScriptFullName)
filePath = filePath & "\test.mdb"
'WScript.Echo filePath

If (fso.FileExists(filePath)) Then
    dim appAccess
    set appAccess = createObject("Access.Application")
    appAccess.visible = true
    appAccess.UserControl = true 'To leave the application open after the script completes you need to set the UserControl property to true.
    appAccess.OpenCurrentDatabase filePath, True, "mypassword"
Else
    WScript.Echo "File doesn’t exist"
End If

如果您将 VBScript 保存在某处,您可以在 C# 中使用

调用它
System.Diagnostics.Process.Start(@"P:\ath\to\Script.vbs");

如果您只需要打开一个数据库连接:

// Declare the path to the database file
var filePath = @"Path\to\database.accdb";

// If statement using File.Exists()
if (File.Exists(filePath))
{ 
    // Create new OleDbConnection object and call Open()
    var conn = new OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath}");
    conn.Open();
}
else
{
    // Write to the console if the file does not exist
    Console.WriteLine("The file does not exist");
}

您需要参考 System.Data.OleDb 才能使用 OleDbConnection,需要参考 System.IO 才能使用 File.Exists()

希望对您有所帮助