ユーザ用ツール

サイト用ツール


it技術:vb2clr

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン前のリビジョン
次のリビジョン
前のリビジョン
it技術:vb2clr [2026/01/30 17:53] – [テキストファイルの読込み] yajuadminit技術:vb2clr [2026/02/02 09:50] (現在) – [テキストファイルの読込み] yajuadmin
行 240: 行 240:
 </code> </code>
  
-=== ReadAllText ===+=== StreamReader(Shift_JIS) === 
 +Shift_JISはエンコードが必要、UTF-8をエンコードで指定してしまうとBOM有無などの自動判別機能がなくなってしまうため、enc を引数として指定しないように修正が必要である。 
 <code vb> <code vb>
 Public Function ReadFile() As Variant Public Function ReadFile() As Variant
行 260: 行 262:
     path = ThisWorkbook.path & "\SJISText.txt"     path = ThisWorkbook.path & "\SJISText.txt"
  
-    ' File.ReadAllText(path) を呼ぶ(静的メソッド) +    ' System.IO.StreamReader(path, enc) を呼ぶ 
-    Dim text As Variant +    Dim reader As mscorlib.Object 
-    text = host.CLRInvokeStaticMethod(filetype, "ReadAllText", path, enc)+    Set reader = host.CLRCreateObjectWithParams("System.IO.StreamReader", path, enc)
          
-    ReadFile CStr(text)+    ' 全文 
 +    Dim text As String 
 +    text host.CLRInvokeMethod(reader, "ReadToEnd") 
 +    host.CLRInvokeMethod reader, "Close" 
 +     
 +    ReadFile = text
  
     Set host = Nothing     Set host = Nothing
 +    Set filetype = Nothing
 +    Set encType = Nothing
 +    Set reader = Nothing
 +End Function
 +</code>
 +=== ReadAllText(Shift_JIS) ===
 +Shift_JISはエンコードが必要、UTF-8をエンコードで指定してしまうとBOM有無などの自動判別機能がなくなってしまうため、enc を引数として指定しないように修正が必要である。
  
 +<code vb>
 +Public Function ReadFile() As Variant
 +
 +    Dim host As New CLRHost
 +    host.Initialize False
 +
 +    host.CLRLoadAssembly ("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
 +
 +    Dim filetype As mscorlib.Type
 +    Set filetype = host.CLRResolveType("System.IO.File")
 +    Dim encType As mscorlib.Type
 +    Set encType = host.CLRResolveType("System.Text.Encoding")
 +    Dim enc As mscorlib.Object
 +    Set enc = host.CLRInvokeStaticMethod(encType, "GetEncoding", "Shift_JIS")
 +    
 +    ' パス
 +    Dim path As String
 +    path = ThisWorkbook.path & "\SJISText.txt"
 +
 +    ' File.ReadAllText(path, enc) を呼ぶ(静的メソッド)
 +    Dim text As String
 +    text = host.CLRInvokeStaticMethod(filetype, "ReadAllText", path, enc)
 +    
 +    ReadFile = text
 +
 +    Set host = Nothing
 +    Set filetype = Nothing
 +    Set encType = Nothing
 +    Set reader = Nothing
 End Function End Function
 </code> </code>
it技術/vb2clr.1769763199.txt.gz · 最終更新: 2026/01/30 17:53 by yajuadmin