2017-03-05 88 views
0

有人可以幫助我將這個腳本轉換爲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 
+0

你需要打開數據庫,以便用戶可以手動訪問它,或者你要插入/查詢以編程方式(使用C#)? – Bassie

回答

0

如果您在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.IOFile.Exists()

希望這有助於

+0

Bassie,打開實際的數據庫(不是連接),我需要OpenCurrentDatabase,因爲我傳遞了數據庫密碼。當然,一個簡單的C#腳本可以實現這一點,而無需安裝其他程序。可以通過使用延遲動態綁定來避免引用? –

+0

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); –

+0

@pdeman我在頂部編輯了我的答案 - 這有幫助嗎?有了這個,你可以像在cs文件中那樣運行你的VBScript。如果需要,您也可以從這裏添加參數 – Bassie