hi, i have written some code that lets the user to upload a file to the root directory of the website. I want the file to be renamed automatically before it is being saved, how do i do this??

using System.IO
string  ImagesFolder = “MyImageFolder”;
string  savePath;
string  saveFile;
savePath = Path.Combine(Request.PhysicalApplicationPath, ImagesFolder);
saveFile = Path.Combine(savePath, FileUpload1.FileName);
FileUpload1.SaveAs(saveFile);

manipulate the filename before creating the saveFile

string newFile = FileUpload1.FileName;
newFile = "myfilename_" + newFile;
saveFile = Path.Combine(savePath, newFile);
commented: thanx for the reply.. worked fine +2

.aspx code

<table>
<tr>
                <td style="height: 21px">
                    File Name
                </td>
                <td style="height: 21px">
                    <input id="File1" style="width: 728px" type="file" runat="server" enableviewstate="true" /></td>
           
           </tr>
</table>

Code Behind

Protected Sub bntSendSMS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bntSendSMS.Click

 Dim dv As DataView = Nothing
        Dim sb As New StringBuilder
        Dim i As Integer


        Dim fname As String
        Dim tempfilename As String
        Dim Pos As Integer
        Dim myfile As FileInfo
        Try

        
            If Utility.ValidateFile(File1.PostedFile.FileName, ".xls") Then
                Pos = File1.PostedFile.FileName.LastIndexOf("\")
                If Pos > 0 Then
                    fname = File1.PostedFile.FileName.Substring(Pos + 1)
                Else
                    fname = File1.PostedFile.FileName
                End If
                tempfilename = Server.MapPath("tempfiles") + "\" + fname
                File1.PostedFile.SaveAs(tempfilename)
                            End If
            Try
                myfile = New FileInfo(tempfilename)
                myfile.Delete()
            Catch ex As Exception
                lblError.Text = ex.Message
            End Try
        Catch ex As Exception
            lblError.Text = ex.Message
        End Try

End Sub

Utillity Class Code to validate your file name

Public Shared Function ValidateFile(ByVal FileName As String, ByVal FileExtension As String) As Boolean
        Dim Fld As Array
        Dim i As Integer
        ValidateFile = False

        Fld = Split(FileName, "\")

        For i = 0 To UBound(Fld)
            If Right(Fld(i), 4) = FileExtension Then
                Return True
            
            End If
        Next
        'If ValidateFile = False Then
        '    ErrMessage = FileName + " NOT a Valid Excel file with " + FileExtension
        'End If
    End Function

Please mark as solved if it helps you!!!!

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.