2010-11-11 26 views
6

什麼是.NET應用程序的內部編碼?(例如字符串對象)我可以定義我的應用程序應該使用什麼編碼?如果我寫一個.net字符串到一個文件。字符串是什麼編碼?.NET內部編碼

//編輯

Dim test as String="Das ist ein Test" <---what Encoding has this String? 

Dim reader as New IO.StreamReader(docPath, _ 
    System.Text.Encoding.GetEncoding("shift-jis")) 

test=reader.ReadToEnd() <---and now? What Encoding has this String? 

謝謝!

回答

5
Dim test as String="Das ist ein Test" <---what Encoding has this String? 

UTF-16

Dim reader as New IO.StreamReader(docPath, 
    System.Text.Encoding.GetEncoding("shift-jis")) 
test=reader.ReadToEnd <---and now? What Encoding has this String? 

儘管如此UTF-16。 StreamReader類查看docPath中的字節,並根據shift-jis編碼將它們轉換爲UTF-16。

+0

+1,以直接查看OP的代碼和有關StreamReader的信息。 – 2010-11-11 14:12:06

1

內部.NET使用統一 - 修訂 - UTF-16。

但是,如果將字符串寫入文件,則必須提供編碼。如果你不.NET將選擇一個編碼 - 這通常是UTF8。 下面是reflectored File.WriteAllText:

public static void WriteAllText(string path, string contents) 
{ 
    if (path == null) 
    { 
     throw new ArgumentNullException("path"); 
    } 
    if (path.Length == 0) 
    { 
     throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); 
    } 
    InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM); 
} 
+1

實際上,它是每個代碼點2個字節,而不是每個字符。重音標記等東西可以是單獨的代碼點,但可以作爲同一個字符的一部分進行打印。此外,它使用UTF-16,這意味着代碼點可能*爲4個字節,但實際上沒有人在基本多語言平面以外使用任何內容。 – 2010-11-11 14:07:38

+0

實際上,它是每個代碼單元2字節,而不是代碼點:-) U + FFFF之上的代碼點需要UTF-16(和.NET用戶UTF-16)中的2個代碼單元。 – 2010-11-13 10:04:36

3

System.String是UTF-16。您可以使用System.Text.Encoding類的衍生產品將其轉換爲各種其他編碼。

在回答編輯: System.IO.StreamReader,據我所知,試圖「猜測」,以正確的編碼,如果沒有指定一個。 System.IO.StreamWriter寫爲UTF-8,IIRC。我對這些類不太熟悉,因此需要您自擔風險;

2

與其他所有答案一樣:是,2字節的Unicode(UTF-16)。是的,你可以控制它如何寫入光盤,就像@Billy ONeal所描述的那樣。

關於你的問題是否可以控制:不,這是不可能的。 .NET將始終在內部運行Unicode UTF-16。這沒有設置。

+0

+1缺少System.String的可變性。 – 2010-11-11 14:12:37

+0

非常感謝:)。 – 2010-11-11 14:21:27