hi all,

im creating a csv file from sql querry, after that im sending this csv file with email, after i sent the mail i wanna delete the csv file but it says 'its using by another....' dont know how to resolve this. thanks for help.

this is my export csv function

Function ExportCsv()
        Dim filePath As String = "C:\FULLWork\csv\limit_dosya.csv"
        Dim delimiter As String = ";"
        Dim sb As New StringBuilder()

        For i As Integer = 0 To DataGridView1.Rows.Count - 1
            Dim array As String() = New String(DataGridView1.Columns.Count - 1) {}

            If i.Equals(0) Then

                For j As Integer = 0 To DataGridView1.Columns.Count - 1
                    array(j) = DataGridView1.Columns(j).HeaderText
                Next
                sb.AppendLine([String].Join(delimiter, array))
            End If

            For j As Integer = 0 To DataGridView1.Columns.Count - 1
                If Not DataGridView1.Rows(i).IsNewRow Then
                    array(j) = DataGridView1(j, i).Value.ToString()
                End If
            Next
            If Not DataGridView1.Rows(i).IsNewRow Then
                sb.AppendLine([String].Join(delimiter, array))
            End If
        Next
        If File.Exists("c:\FULLWork\csv\limit_dosya.csv") Then
            File.Delete("c:\FULLWork\csv\limit_dosya.csv")
        Else
            File.WriteAllText(filePath, sb.ToString(), System.Text.Encoding.Default)
        End If
    End Function

and my send mail function

Function MailGonder()
        Dim mail As New MailMessage()
        mail.From = New MailAddress("baris.sen@full.com.tr")
        mail.[To].Add("kurumsalsatis@full.com.tr,baris.sen@full.com.tr,tevhit.kocabey@full.com.tr")
        mail.Subject = "Limit Dosyası"
        mail.Body = "Limit Dosyası Ektedir."


        Dim smtp As New SmtpClient("EXCHANGE.asya.local")
        smtp.Credentials = New Net.NetworkCredential("baris.sen", "password")
        Dim oAttch As Net.Mail.Attachment = New Net.Mail.Attachment("c:\FULLWork\csv\limit_dosya.csv")
        mail.Attachments.Add(oAttch)
        Try
            smtp.Send(mail)
        Catch exc As Exception

        End Try
    End Function

You will have to read/write from a stream.

If you use the File.IO methods, you are holding that file until the application exits.

I know you might not have to worry about it from the regulars, but the anons might take advantage of the private information.

You might want to remove that information from your code snippet.

fixed it with adding oAttch.Dispose() thanks for reply

You can put a class into using statement, this way it will Dispose() automatically when exiting the loop.

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.