Convert a VBScript to C#

房东的猫 提交于 2019-12-25 06:53:36

问题


Can some one help me converting this script to C# I am still very much a begiiner and learning in C#. The script uses OpenCurrentDatabase to open (and keep open) an Access .mdb file, I must use this method and the code as it is but converted to C#, any help would be very much appreciated.

I’m using notepad to edit the cs file and csc.exe to compile it (I don’t have any other C# tools).

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

回答1:


If you have your VBScript saved somewhere you can call it from within C# with

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

If you just need to open a connection to the database:

// 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");
}

You will need to reference System.Data.OleDb to use OleDbConnection, and System.IO for File.Exists()

Hope this helps



来源:https://stackoverflow.com/questions/42610844/convert-a-vbscript-to-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!