Solved

Can't Delete File

Posted on 2012-04-03
5
213 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
Comment Utility
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
Comment Utility
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
Comment Utility
Try adding it to both ffmpeg.WaitForExit() and ffmpegThumb.WaitForExit().
0
 

Author Comment

by:ntd1
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

763 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now