我需要保存空字符"\0"
与其他人一起nvarchar
我的 SQL 数据库中的列。但是,这样做会忽略第一个 "\0"
之后的所有字符。 , 所以如果这是在字符串的开头,一个空字符串值将被保存到数据库中。
下面的这个例子将一个空字符串保存到 Text
nvarchar
列专栏。
TestEntities te = new TestEntities();
te.Table_1.Add(new Table_1 { Text = "\0tes\0 ttest \0" });
te.SaveChanges();
此示例将保存文本 tes
的位置.
TestEntities te = new TestEntities();
te.Table_1.Add(new Table_1 { Text = "tes\0test" });
te.SaveChanges();
是否有对此行为的解释以及我可以解决此问题的任何方法?
编辑:阅读答案后,SQL 在 "\0"
之后终止字符串character 我正在将我的字符串转换为 Base64 字符串。下面的例子。
static void Main(string[] args)
{
TestEntities te = new TestEntities();
string value = "tes\0 ttest \0";
Table_1 table = new Table_1 { Text = Base64Encode(value) };
te.Table_1.Add(table);
te.SaveChanges();
string text = Base64Decode(table.Text);
}
public static string Base64Encode(string plainText)
{
byte[] bytes = new byte[plainText.Length * sizeof(char)];
System.Buffer.BlockCopy(plainText.ToCharArray(), 0, bytes, 0, bytes.Length);
return System.Convert.ToBase64String(bytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
char[] chars = new char[base64EncodedBytes.Length / sizeof(char)];
System.Buffer.BlockCopy(base64EncodedBytes, 0, chars, 0, base64EncodedBytes.Length);
return new string(chars);
}
这会产生输出 dABlAHMAAAAgAHQAdABlAHMAdAAgAAAA
从我的原始值 tes\0 ttest \0
最佳答案
恐怕 SQL 会将 \0
视为字符串的结尾。
尝试将数据存储为 var 二进制并使用:
System.Text.Encoding.UTF8.GetBytes("\0tes\0 ttest\0")
写入和
System.Text.Encoding.UTF8.GetString(table.Text)
读取。
关于c# - 使用 Entity Framework 将字符串值保存到 SQL 表中,该表包含 Null 字符,所有后续字符的剪切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23543529/