Hi,

I am creating a text file using a save file dialog and copying the path to the text box which file is used to write from vb.net. when i try to write i get an error "The process cannot access the file '....fileName.txt' because it is being used by other program". How to resolve this

The code is below

Public Sub writeInTextFile()
        Try
            Dim oWrite As New StreamWriter(TxtOutputPath.Text)
            Dim colnCt, rowCt As Integer
            colnCt = GridDataOutField.Columns.Count
            rowCt = GridDataOutField.Rows.Count
            Dim gridData As String = ""

            For i As Integer = 0 To colnCt - 1
                If i = 0 Then
                    gridData = GridDataOutField.Columns(i).Name
                Else
                    gridData += vbTab + GridDataOutField.Columns(i).Name
                End If

            Next
            oWrite.WriteLine(gridData)

            For i As Integer = 0 To rowCt - 2
                gridData = ""
                For j As Integer = 0 To colnCt - 1
                    If j = 0 Then
                        gridData = GridDataOutField.Item(j, i).Value
                    Else
                        gridData += vbTab + GridDataOutField.Item(j, i).Value
                    End If
                Next
                oWrite.WriteLine(gridData)
            Next
            MsgBox("Sucessfully written to the selected path")
            oWrite.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

Check if the file open while you are trying to write to it.

hi..try this method..........

Dim filelocation as string =source & "file.txt"
  Dim fs As New FileStream(filelocation, FileMode.Create, FileAccess.Write)
 Dim writer As New StreamWriter(fs)
writer.writeline("mention login time") 'Here mention store variable  login time
writer.writeline("mentionlogouttime")
writer.close()
end sub

Even if you had any doubt ..try this link...
[blog link snipped]

This has never given me any issues with "The process cannot access the file '...' because it is being used by other program.".

Dim myFile As String = "C:\test.txt"
        IO.File.WriteAllText(myFile, "text to save here")

codeorder's solution seems the best ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.