如何在SQL Server中保存带有中文字符的文件名 - Varchar(100)?

时间:2017-10-04 12:41:21

标签: c# sql-server

我的文件名是这样的:一个例子.pdf

我想将文件名保存在SQL Server表中,并从SQL Server表中读取它。你是怎么做到的?

这是代码:

class Bestand
{
        public void Add(string filePath, DateTime fileDate, string fileName = "")
        {
            Bestand bestand = this.CurrentBestand;

            if (filePath.Length > 0 && CanReadFile(filePath))
            {
                Binary bin = new Binary();
                bin.Data = new System.Data.Linq.Binary(File.ReadAllBytes(filePath));

                bestand.BestandsDatum = fileDate;
                bestand.BestandsNaam = String.IsNullOrEmpty(fileName) ? Path.GetFileName(filePath) : Encoding.UTF8.GetBytes(fileName)[0].ToString();  

                bestand.Binary = bin;
            }
        }

        public void Save(string filePath)
        {
            byte[] buffer = Data.ToArray();
            System.IO.File.WriteAllBytes(filePath, buffer);
        }
…
}

并调用此方法保存文件:

documents[0].Add(beFile.Value, dtpDate.Value);

并调用此方法打开文件:

public static void ViewBestand(IBestand bestand)
{
    string orgFilepath = Path.Combine(TempDocumentFolder, bestand.FileName);
    string filepath = orgFilepath;

    int tmpCounter = 0;
    while (File.Exists(filepath) && tmpCounter < 100)
    {
        tmpCounter++;
        filepath = Path.Combine(TempDocumentFolder, Path.GetFileNameWithoutExtension(orgFilepath) + "_" + tmpCounter.ToString() + Path.GetExtension(orgFilepath));
    }

    bestand.Save(filepath);
    ViewFile(filepath);
}

1 个答案:

答案 0 :(得分:5)

将列的类型更改为nvarchar(100)varchar无法存储Unicode字符,因为它是单字节,Unicode是双字节。

您可以阅读here