将VBScript转换为C#
有人可以帮助我将这个脚本转换为C#我仍然是一个初学者,并在C#中学习。该脚本使用OpenCurrentDatabase打开(并保持打开)一个Access .mdb文件,我必须使用此方法和代码,因为它是,但转换为C#,任何帮助将非常感激。将VBScript转换为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的地方保存就可以与
System.Diagnostics.Process.Start(@"P:\ath\to\Script.vbs");
从C#中调用它。如果你只需要打开一个到数据库的连接:
// 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()
希望这有助于
Bassie,打开实际的数据库(不是连接),我需要OpenCurrentDatabase,因为我传递了数据库密码。当然,一个简单的C#脚本可以实现这一点,而无需安装其他程序。可以通过使用延迟动态绑定来避免引用? –
Bassie可以将我的vbscript行添加到下面的代码中吗?我得到的GUI错误不会编译?这将如何完成? 类型scriptType = Type.GetTypeFromCLSID(Guid.Parse(“0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC”)); dynamic obj = Activator.CreateInstance(scriptType,false); obj.Language =“vbscript”; string vbscript =“msgbox(\”test \“)”; obj.Eval(vbscript); –
@pdeman我在顶部编辑了我的答案 - 这有帮助吗?有了这个,你可以像在cs文件中那样运行你的VBScript。如果需要,您也可以从这里添加参数 – Bassie
你需要打开数据库,以便用户可以手动访问它,或者你要插入/查询以编程方式(使用C#)? – Bassie