Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Can't Delete File

Posted on 2012-04-03
5
216 Views
Last Modified: 2012-06-21
Hi
 
I am developing a video uploading website. It is working fine apart from one problem. When a user uploads a video file it is converted into flv using ffmpeg both files are in a user specified folder (a copy of their original, the converted file and also a thumbnail image file captured during conversion).

I would however like to delete the original video file after the conversion process, but I am unable to get it to work. The upload is fired through a button click and the conversion sub is called during that, with the delete file at the end of that.
 
My code is below:
 
Thanks

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
 
        If IsPostBack Then
            'declare the file path to store uploads
            Dim path As String = Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/")
            'Dim path As String = HttpRuntime.AppDomainAppPath ("~/UploadedVideos/" & UserLogin.UserNo & "/")
 
            Dim fileOK As Boolean = False
 
            'If the file upload control has a file and it is less than the maximum file size limit of 200MB
            If FileUploadVideo.HasFile And FileUploadVideo.PostedFile.ContentLength < 209715200 Then
 
                'check to see if the number of characters does not exceed 50 and is not empty
                If Len(txtVideoName.Text) <= 50 And txtVideoName.Text IsNot "" Then
                    'clear the error message
                    lblErrorTitle.Text = "" 
 
                    ' check to see if a course has been added to the list
                    If lstCourses.Items.Count > 0 Then
                        lblErrorCourse.Text = "" 
                        'check to see if a module has been added to the list
                        If lstModules.Items.Count > 0 Then
                            lblErrorModule.Text = "" 
                            If Len(txtDescription.Text) <= 500 And txtDescription.Text IsNot "" Then
                                lblDescriptionError.Text = "" 
 
                                'check to see if the number of characters does not exceed 50 and is not empty
                                If Len(txtKeywords.Text) <= 50 And txtKeywords.Text IsNot "" And txtKeywords.Text = Replace(txtKeywords.Text, " ", "") Then
 
                                    'clear the error message
                                    lblErrorKeywords.Text = "" 
 
                                    'check the file to make sure it is of the required type
                                    Dim fileExtension As String
                                    fileExtension = System.IO.Path. _
                                        GetExtension(FileUploadVideo.FileName).ToLower()
                                    'declare the allowed extentions
                                    Dim allowedExtensions As String() = _
                                        {".mov", ".wmv", ".avi", ".mp4", ".m4v"}
                                    'loop to check the extention type
                                    For i As Integer = 0 To allowedExtensions.Length - 1
                                        If fileExtension = allowedExtensions(i) Then
 
 
                                            '******************* Convert Video File *******************************
 
 
                                            Call encode()
 
 
                                            fileOK = True
 
                                        End If
 
 
 
                                    Next
                                    If fileOK Then
 
                                        '******************* Write Video Details into the Database *******************************
 
                                        Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
                                            Try
 
 
                                                Dim FilePath = fileNameWithoutExtention & ".flv"
                                                'Dim FilePath = path & FileUploadVideo.FileName
                                                'insert statement to add the video details to the database
                                                ' SqlCommand(cmd = New SqlCommand("GetAllData", connection))
 
                                                'open the database connection
                                                Conn.Open()
 
 
                                                '******************* Create XML lists for multiple courses and modules *******************************
                                                'delare variables for xml lists
                                                Dim oXml As New XmlDocument
                                                Dim oNode As XmlNode
                                                Dim oNode2 As XmlNode
                                                Dim oElement As XmlElement
                                                Dim oElement2 As XmlElement
 
 
 
                                                Dim xmlCourse As String
                                                'declare the xmlnode
                                                Dim pNode As XmlNode = oXml.CreateElement("Courses")
                                                oXml.AppendChild(pNode)
 
                                                oNode = oXml.SelectSingleNode("Courses")
                                                'loop through the list
                                                For i As Integer = 0 To lstCourses.Items.Count - 1
                                                    If lstCourses.Items(i).Selected = True Then
                                                        oElement = oXml.CreateElement("CourseNo")
                                                        oElement.InnerText = lstCourses.Items(i).Value
                                                        oNode.AppendChild(oElement)
                                                    End If
                                                Next
 
                                                xmlCourse = oXml.InnerXml
 
                                                Dim xmlModule As String
 
                                                Dim oXml2 As New XmlDocument
                                                Dim pNode2 As XmlNode = oXml2.CreateElement("Modules")
                                                oXml2.AppendChild(pNode2)
 
                                                oNode2 = oXml2.SelectSingleNode("Modules")
                                                'loop through the list
                                                For i As Integer = 0 To lstModules.Items.Count - 1
                                                    If lstModules.Items(i).Selected = True Then
                                                        oElement2 = oXml2.CreateElement("ModuleNo")
                                                        oElement2.InnerText = lstModules.Items(i).Value
                                                        oNode2.AppendChild(oElement2)
                                                    End If
                                                Next
 
                                                xmlModule = oXml2.InnerXml
 
                                                'assign the stored procedure
                                                Const SQL As String = "sprocUploadVideo"
                                                Dim cmd As New SqlCommand(SQL, Conn)
                                                cmd.CommandType = CommandType.StoredProcedure
                                                cmd.Parameters.AddWithValue("@UserNo", UserLogin.UserNo())
                                                cmd.Parameters.AddWithValue("@VideoName", txtVideoName.Text.Trim())
                                                cmd.Parameters.AddWithValue("@CourseXML", xmlCourse)
                                                cmd.Parameters.AddWithValue("@ModuleXML", xmlModule)
                                                cmd.Parameters.AddWithValue("@DateUploaded", Date.Now)
                                                cmd.Parameters.AddWithValue("@VideoUrl", UserLogin.UserNo & "/" & fileNameWithoutExtention & ".flv")
                                                cmd.Parameters.AddWithValue("@ThumbUrl", UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg")
                                                cmd.Parameters.AddWithValue("@Description", txtDescription.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Keywords", txtKeywords.Text.Trim())
                                                cmd.Parameters.AddWithValue("@Visible", "Yes")
                                                FileUploadVideo.PostedFile.SaveAs(path & _
                                                     FileUploadVideo.FileName)
                                                'Successful upload message
                                                lblError.Text = "File Uploaded Successfully - Thank You"
                                                btnYourVideos.Visible = True
                                                'clear the fields  
                                                lblHoldFilePath.Text = "" 
                                                lstModules.Items.Clear()
                                                lstCourses.Items.Clear()
                                                txtVideoName.Text = "" 
                                                txtKeywords.Text = "" 
                                                cboCourse.Text = "" 
                                                cboModule.Text = "" 
                                                txtDescription.Text = "" 
                                                cmd.ExecuteNonQuery()
 
                                                'close the database connection
                                                Conn.Close()
                                            Catch ex As Exception
 
                                                'file can't be uploaded error message
                                                lblError.Text = "File could not be uploaded." & ex.Message
                                            End Try
                                        End Using
                                    Else
                                        'error message for incorrect file type
                                        lblError.Text = "Cannot accept files of this type."
                                    End If
 
 
                                Else
                                    'error message for too many characters in the video name field
                                    lblErrorKeywords.Text = "This is a required field with a maximum length of 50 characters and no spaces!"
                                End If
 
 
                            Else
                                'error message for too many characters in the video description field
                                lblDescriptionError.Text = "This is a required field with a maximum length of 500 characters"
 
 
                            End If
 
                        Else
                            'error message for no modules on the list
                            lblErrorModule.Text = "You must add at least 1 Module to the list"
                        End If
                    Else
                        'error message for no courses on the list
                        lblErrorCourse.Text = "You must add at least 1 course to the list"
                    End If
 
                Else
                    'error message for too many characters in the keywords field
                    lblErrorTitle.Text = "This is a required field with a maximum length of 50 characters"
                End If
 
 
            Else
                'error message for no file selected
                lblHoldFilePath.Text = "Please choose a file which must be less than 200MB!!"
            End If
        End If
 
 
    End Sub
     
    '******************* Video encode settings *******************************
    Sub encode()
        Dim ffmpeg As Process
        ' creating process
        Dim fileName As String = FileUploadVideo.FileName
        'remove previous extension from file
        fileNameWithoutExtention = fileName.Substring(0, fileName.LastIndexOf("."))
        video = Page.MapPath("UploadedVideos\\" & UserLogin.UserNo & "\" & fileName)
        ' setting video input name with path
        mpg = Page.MapPath("") & "\UploadedVideos\" & UserLogin.UserNo & "\" & fileNameWithoutExtention & ".flv"
        ' thumb name with path !
        ffmpeg = New Process()
 
        ffmpeg.StartInfo.Arguments = " -i """ & video & """ -qscale 6 -f flv """ & mpg & """"
        'ffmpeg.StartInfo.Arguments = " -qscale 4 -i """ & video & """ -f flv - | ~/ffmpeg/flvtool2 -U stdin """ & mpg & """"
 
        ffmpeg.StartInfo.FileName = Page.MapPath("ffmpeg/ffmpeg.exe")
        ffmpeg.Start()
        ffmpeg.Close()
 
 
        '******************* Video thumbnail capture settings *******************************
        Dim ffmpegThumb As Process
        'grab thumbnail from video during the encode process
        Dim thumb As String
        video = Page.MapPath("UploadedVideos\\" & UserLogin.UserNo & "\" & fileName)
        ' ' setting video input name with path
        thumb = Page.MapPath("") & "\UploadedVideos\" & UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg"
        ' ' thumb name with path !
        ffmpegThumb = New Process()
        ' arguments !
        ffmpegThumb.StartInfo.Arguments = " -i """ & video & """ -s 180*101 -vframes 1 -ss 5 -f image2 -vcodec mjpeg """ & thumb & """"
        ffmpegThumb.StartInfo.FileName = Page.MapPath("ffmpeg/ffmpeg.exe")
        ffmpegThumb.Start()
        ffmpegThumb.Close()
        'delete the original file
        File.Delete(video)
    End Sub
0
Comment
Question by:ntd1
  • 3
  • 2
5 Comments
 
LVL 23

Expert Comment

by:wdosanjos
ID: 37802125
It seems the ffmpeg.exe process is still running when you try to delete the file.  Try adding a ffmpegThumb.WaitForExit() call between ffmpegThumb.Start() and ffmpegThumb.Close() as follows:

        ffmpegThumb.Start()
        ffmpegThumb.WaitForExit()
        ffmpegThumb.Close()
        'delete the original file
        File.Delete(video) 

Open in new window

0
 

Author Comment

by:ntd1
ID: 37802221
Hi

I tried that. But it failed on both (image and video). So I added the line to the video part ffmpeg.WaitForExit() but it gave me just the image and still left the original video file?

The video process runs longer than the image capture even though it starts afterwards.
0
 
LVL 23

Accepted Solution

by:
wdosanjos earned 500 total points
ID: 37802604
Try adding it to both ffmpeg.WaitForExit() and ffmpegThumb.WaitForExit().
0
 

Author Comment

by:ntd1
ID: 37802844
Hi

I have tried the following which now converts the video ok deletes the video file but doesn't get the image.It says no such file or directory. If you notice I have moved the line of code that moves the file from the upload path to the directory into the encode sub:

 Sub encode()
        'declare the file path to store uploads
        Dim path As String = Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/")
        FileUploadVideo.PostedFile.SaveAs(Path & FileUploadVideo.FileName)
        Dim fileName As String = FileUploadVideo.FileName
        '******************* Video thumbnail capture settings *******************************
        Dim ffmpegThumb As Process
        'grab thumbnail from video during the encode process
        Dim thumb As String
        video = Page.MapPath("UploadedVideos\\" & UserLogin.UserNo & "\" & fileName)
        '    ' setting video input name with path
        thumb = Page.MapPath("") & "\UploadedVideos\" & UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg"
        '    ' thumb name with path !
        ffmpegThumb = New Process()
        ' arguments !
        ffmpegThumb.StartInfo.Arguments = " -i """ & video & """ -s 180*101 -vframes 1 -ss 10-f image2 -vcodec mjpeg """ & thumb & """"
        ffmpegThumb.StartInfo.FileName = Page.MapPath("ffmpeg/ffmpeg.exe")
        ffmpegThumb.Start()
        ffmpegThumb.WaitForExit()
        ffmpegThumb.Close()

        '******************* Video encode settings *******************************
        Dim ffmpeg As Process
        ' creating process

        'remove previous extension from file
        fileNameWithoutExtention = fileName.Substring(0, fileName.LastIndexOf("."))
        video = Page.MapPath("UploadedVideos\\" & UserLogin.UserNo & "\" & fileName)
        ' setting video input name with path
        mpg = Page.MapPath("") & "\UploadedVideos\" & UserLogin.UserNo & "\" & fileNameWithoutExtention & ".flv"
        ' thumb name with path !
        ffmpeg = New Process()
        ffmpeg.StartInfo.Arguments = " -i """ & video & """ -ab 56 -ar 44100 -r 15 -qscale 6 -f flv """ & mpg & """"
        'ffmpeg.StartInfo.Arguments = " -i """ & video & """ -qscale 6 -f flv """ & mpg & """"
        'ffmpeg.StartInfo.Arguments = " -qscale 4 -i """ & video & """ -f flv - | ~/ffmpeg/flvtool2 -U stdin """ & mpg & """"
        ffmpeg.StartInfo.FileName = Page.MapPath("ffmpeg/ffmpeg.exe")
        ffmpeg.Start()
        ffmpeg.WaitForExit()
        ffmpeg.Close()


       
        'delete the original file
        File.Delete(Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/" & FileUploadVideo.FileName))
        'Empty session
        Session("VideoFileUpload1") = Nothing
    End Sub
0
 

Author Comment

by:ntd1
ID: 37802985
Hi

I managed to get it to work doing the following: Thanks for your help

'******************* Video encode settings *******************************
    Sub encode()
        'declare the file path to store uploads
        Dim path As String = Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/")
        'Dim path As String = HttpRuntime.AppDomainAppPath ("~/UploadedVideos/" & UserLogin.UserNo & "/")
        FileUploadVideo.PostedFile.SaveAs(path & FileUploadVideo.FileName)

        Dim ffmpeg As Process
        ' creating process
        Dim fileName As String = FileUploadVideo.FileName
        'remove previous extension from file
        fileNameWithoutExtention = fileName.Substring(0, fileName.LastIndexOf("."))
        video = Page.MapPath("UploadedVideos\\" & UserLogin.UserNo & "\" & fileName)
        ' setting video input name with path
        mpg = Page.MapPath("") & "\UploadedVideos\" & UserLogin.UserNo & "\" & fileNameWithoutExtention & ".flv"
        ' thumb name with path !
        ffmpeg = New Process()
        ffmpeg.StartInfo.Arguments = " -i """ & video & """ -ab 56 -ar 44100 -r 15 -qscale 6 -f flv """ & mpg & """"
        'ffmpeg.StartInfo.Arguments = " -i """ & video & """ -qscale 6 -f flv """ & mpg & """"
        'ffmpeg.StartInfo.Arguments = " -qscale 4 -i """ & video & """ -f flv - | ~/ffmpeg/flvtool2 -U stdin """ & mpg & """"
        ffmpeg.StartInfo.FileName = Page.MapPath("ffmpeg/ffmpeg.exe")
        ffmpeg.Start()
        ffmpeg.WaitForExit()
        'close the process
        ffmpeg.Close()


        '******************* Video thumbnail capture settings *******************************
        Dim ffmpegThumb As Process
        'grab thumbnail from video during the encode process
        Dim thumb As String
        video = Page.MapPath("UploadedVideos\\" & UserLogin.UserNo & "\" & fileName)
        'setting video input name with path
        thumb = Page.MapPath("") & "\UploadedVideos\" & UserLogin.UserNo & "\" & fileNameWithoutExtention & ".jpg"
        'thumbnail name with path !
        ffmpegThumb = New Process()
        ' arguments !
        ffmpegThumb.StartInfo.Arguments = " -i """ & video & """ -s 180*101 -vframes 1 -ss 10 -f image2 -vcodec mjpeg """ & thumb & """"
        ffmpegThumb.StartInfo.FileName = Page.MapPath("ffmpeg/ffmpeg.exe")
        ffmpegThumb.Start()
        ffmpegThumb.WaitForExit()
        'close the process
        ffmpegThumb.Close()

        'delete the original file
        File.Delete(Server.MapPath("~/UploadedVideos/" & UserLogin.UserNo & "/" & FileUploadVideo.FileName))

        'Empty session
        Session("VideoFileUpload1") = Nothing
    End Sub
    Protected Sub btnAddCourse_Click(sender As Object, e As System.EventArgs) Handles btnAddCourse.Click

        'check if an item is selected
        If cboCourse.SelectedIndex <> 0 Then
            'check to see selected item is not already on the list
            If lstCourses.Items.Contains(cboCourse.SelectedItem) = True Then
                'tell user duplicates can't be added
                lblErrorCourse.Text = "This Course is Already on the List!"
            Else
                'clear the error message
                lblErrorCourse.Text = ""
                'if ok add to the list
                lstCourses.Items.Add(cboCourse.SelectedItem)

            End If
        Else
            'error message no course selected
            lblErrorCourse.Text = "Please First Select a Course"
        End If


    End Sub
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
IIS redirect 1 77
How can I run RAW complex query's with Entity Framework Core 1 37
Where is this file? 3 25
Running powershell scripts from ASP.NET 6 27
Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question