开发者

Cannot save foreign text to a SQL Server database table with a nvarchar field

开发者_如何学GoI have a requirement to have a multiline textbox that accepts any text from any language and stores this into the database for later use.

I am using Linq with ASP .NET 3.5 with a SQL Server 2005 database.

Any/all information you can provide me with is much appreciated :D


You'll need to Encode and Decode the text depending if you're updating/inserting or Viewing the data.

Look at System.Text.Encoding


After a lot of research and fretting I found a some stuff I pieced together and used to come up with my ultimate solution. This handles being able to insert any character I could throw at it:

I created 2 methods to handle the 2 scenarios I was looking to solve.

1st going from the user interface to the database. I made sure that my web page was sporting the Unicode(utf-8) encoding content type.

public string unicodeToIso(string InStr)
    {
        if (InStr != null)
        {
            Encoding iso = Encoding.GetEncoding(1252);
            Encoding unicode = Encoding.Unicode;
            byte[] unicodeBytes = unicode.GetBytes(InStr);

            return iso.GetString(unicodeBytes);
        }
        else
            return null;
    }

Then I handled the return of the data to the user interface.

public string isoToUnicode(string InStr)
    {
        if (InStr != null)
        {
            // I originally used the string: "iso8859-1" instead of 1252
            // 1252 helped 'catch' ALL of the Chinese characters as opposed to most
            Encoding iso = Encoding.GetEncoding(1252); 
            Encoding unicode = Encoding.Unicode;
            byte[] isoBytes = iso.GetBytes(InStr);

            return unicode.GetString(isoBytes);
        }
        else
            return null;
    }

I truly hope this helps anyone else out there that may be stumbling on this same problem :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜