Correctly get win-1252 text stored in SQL Server

393 Views Asked by At

I have a legacy WPF app (on .NET 4.7) that reads files from the drive as string in win 1252 encoding. Then it stores the string in a text column in a database table.

I have a new console app (.NET Core 6) and I am trying to get the column which contains the contents of a file in 1252 encoded text and create the same file on another file system.

However, doing that, the files end up corrupted when I try to open them although I can open them without a problem from the legacy app.

Here is the code that I get the contents from the text column and then use it to write a new file in the file system:

var content = _dBContext.Docs.Where(e => e.Id == id).Select(e => e.Contents).SingleOrDefault();
byte[] encodedAnsi = Encoding.GetEncoding(1252).GetBytes(content);
string correctedUtf = Encoding.UTF8.GetString(encodedAnsi);
byte[] correctedArr = Encoding.UTF8.GetBytes(correctedUtf);
File.WriteAllBytes(filename, correctedArr);

Also here is the legacy code that stores the file contents in the database:

Function GetContent(ByVal FName As String) As String

Dim buffa As String
Dim Input As FileStream = New FileStream(FName, FileMode.Open, FileAccess.Read)
Dim Bytes(CInt(Input.Length - 1)) As Byte
Input.Read(Bytes, 0, CInt(Input.Length))
Input.Close()
buffa = System.Text.Encoding.Default.GetString(Bytes)
ReadFileX = buffa
If Len(buffa) = 0 Then ReadFileX = ""
End Function

.......... 
Dim content As String = GetContent(filepath)
..........

Update Docs Set Contents = " & content & " Where Id = " & id

My goal is to just correctly write the file in a new filesystem by getting the file contents from the Text column and therefore i should be able to open those files when i execute them. Now they seem corrupted when i try to open them.

Could someone help?

Although the code is

System.Text.Encoding.Default.GetString(Bytes)

I run on powershell on the server the legacy app is running:

[System.Text.Encoding]::Default 

and I got back that the default encoding is win-1252 so I guess I am not making a wrong assumption there

0

There are 0 best solutions below