Changing the encoding of a textfile

Sometimes it would be a lot easier, if english were the only language – this would really make it easier to be a programmer working with files and encoding.

I’m currently programming some sort of podcast-application, and for this, I have to read a textfile, that contains information about the videos to cast. But, when I read the text from the file into my textbox, I missed a lot of characters… All the danish characters.

Therefore I created a small function to change the encoding from (in my case ANSI) to UTF-8.

If there are better ways to do this – then please let me know. I don’t know if it works for large files, but for the small files I’m working with, it works great.

 

    ''' <summary>
    ''' Chaging the encoding of a file
    ''' </summary>
    ''' <param name="InputFile">Takes a reference to the inputfile as a string (location)</param>
    ''' <returns>A string with a reference to the new file</returns>
    ''' <remarks></remarks>
    Private Function ChangeEncoding(ByVal InputFile As String) As String
        Try
            'Opening a textreader to hold the content of the file in default encoding.
            Dim input As TextReader = New StreamReader(New FileStream(InputFile, FileMode.Open), Encoding.Default)
            'Generating af new filename
            Dim strFile As String = Path.GetFileNameWithoutExtension(Path.GetRandomFileName).ToString & ".txt"
            'Writing the text to a new file
            My.Computer.FileSystem.WriteAllText(My.Settings.TxtRootFolder & "\" & strFile, input.ReadToEnd, False)
            'Closing the input-file
            input.Close()
            'Deleting the original file
            If My.Computer.FileSystem.FileExists(InputFile) Then
                My.Computer.FileSystem.DeleteFile(InputFile)
            End If
            'Returning the name of the new file to the caller
            Return strFile.ToString
        Catch ex As Exception
            'Trowing an exception back to the caller
            Throw New Exception(ex.Message, ex.InnerException)
            Return String.Empty
        End Try
    End Function

 

Technorati: , , ,

Leave a Comment