簡體   English   中英

如何通過C#獲取存儲庫git中文件的編碼?

[英]How to get the encoding of a file in a repository git via C#?

有誰知道一種方法來檢索C#中git存儲庫中存儲的文件的編碼? 我嘗試使用WebClient通過URL檢索內容,並使用DownloadString方法檢索文件的內容,但是它並不真正適合我想要的內容。 它以doctype返回HTML頁面的內容,因此其編碼不是存儲文件的編碼,而是html文件的編碼。

 WebClient client = new WebClient();
 try
 {
   client.DownloadString(filename);
 }
 catch (webexception we)
 {
    logger.writelinelog(we.message + "\n" + we.status.tostring());
 }

最后,我可以找到解決方案:因為這是簡單地檢查存儲過程是否在UTF-8中的問題,所以我在C#中進行如下操作:我們可以從流中檢測編碼UTF 8 BOM的類型。 ,對於UTF8,我在流中檢查了一個特殊字符(以進行改進),在這種情況下,所有不適合的內容都不是UTF-8

非常感謝你的幫助。

public static Encoding GetFileEncoding(GitRepository repository, GitItem gitItem)
    {
        GitVersionDescriptor versionDesc = !string.IsNullOrEmpty(Configuration.Branch) ? new GitVersionDescriptor()
        {
            VersionType = GitVersionType.Branch,
            Version = Configuration.Branch,
            VersionOptions = GitVersionOptions.None
        } : null;

        using (Stream stream = GitClient.GetItemContentAsync(repository.Id, gitItem.Path, download: false, versionDescriptor: versionDesc, includeContentMetadata: true, includeContent: true).Result)
        {
            var bom = new byte[4];
            stream.Read(bom, 0, 4);
            // Analyze the BOM
            if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
            if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
            if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
            if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
            if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
            using (StreamReader reader = new StreamReader(stream, true))
            {
                reader.Peek();
                if (reader.ReadToEnd().Contains('�'))
                {
                    return Encoding.ASCII;
                }
                return Encoding.UTF8;
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM