SSIS 脚本任务 System.IO.File.WriteAllText 引发 "The process cannot access the file" 错误

SSIS Script Task System.IO.File.WriteAllText throws "The process cannot access the file" Error

我的任务是编写一个 SSIS 包,自动创建 SQL 服务器数据库。在此过程中,它需要创建一个 DSN 文件(文本文件),以便 Access 工具可以连接到 SQL 服务器数据库。这都是遗留问题,我无法更改要求。我也无法改变我在 Visual Studio 2005 年使用 VB.NET.

工作的事实

问题是,当我尝试写入 DSN 文件时出现错误:"The process cannot access the file '\Acmshares2\clntrial\DataMgt\DM_DSNs\DM_C001.dsn' because it is being used by another process."正在创建文件,但我无法写入。就好像创建文件的行以某种方式 "holding on" 一样。这是代码 - 请注意,无论行 System.IO.File.OpenWrite(sFilePath) 是否存在,都会引发错误:

Public Sub Main()
    Dim sStudyID As String
    Dim sText As String
    Dim sFileName As String
    Dim sFilePath As String

    If Dts.Variables.Contains("StudyID") = True Then
        sStudyID = CType(Dts.Variables("StudyID").Value, String)
    End If

    sText = "[ODBC]" & vbCrLf
    sText = sText & "DRIVER=SQL Server" & vbCrLf
    sText = sText & "UID=DM" & vbCrLf
    sText = sText & "DATABASE=DM_" & sStudyID & vbCrLf
    sText = sText & "WSID=ACMDM" & vbCrLf
    sText = sText & "APP=Microsoft Data Access Components" & vbCrLf
    sText = sText & "SERVER=ACMDM" & vbCrLf

    sFileName = "DM_" & sStudyID & ".dsn"
    sFilePath = "\Acmshares2\clntrial\DataMgt\DM_DSNs\" & sFileName

    If Not System.IO.File.Exists(sFilePath) Then
        System.IO.File.Create(sFilePath)
    End If
    System.IO.File.OpenWrite(sFilePath)
    System.IO.File.WriteAllText(sFilePath, sText)

    Dts.TaskResult = Dts.Results.Success
End Sub

任何帮助将不胜感激!

WriteAllText() 创建一个新文件或覆盖任何现有文件,因此您不需要 Create()OpenWrite() 调用。