/// <summary> /// テキストファイルを読み込みます /// TextEncodingプロパティが null の場合は、文字コードの判別を行います /// NewLineCode プロパティが null の場合は、改行コードの判別を行います /// 引数で自動判別のフラグを持たさせたいが、I/F合わなくなるため、追加していません。要検討。 /// </summary> /// <param name="path">パス</param> public void Load(string path = null) { if (path == null) { path = this.Path; } if ((new FileInfo(path)).Length >= 1024 * 1024 * 50) { //ファイルサイズが50MBを超える場合はエラーとする。TODO:Configで設定させる throw new Exception("ファイルサイズが50MBを越えています。"); } byte[] byteArray; using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); } //16進数の文字列をテキストとして設定します this.Text = BinaryUtils.ByteArrayToHex(byteArray, 16); //パス、読み込み専用のフラグの保持 this.Path = path; this.IsReadOnly = FileUtils.IsReadOnly(path); }
public void HexToByteArrayTest() { { string hex = "00 01 fe ff"; byte[] byteArray = BinaryUtils.HexToByteArray(hex); Assert.AreEqual(byteArray[0], 0); Assert.AreEqual(byteArray[1], 1); Assert.AreEqual(byteArray[2], 0xfe); Assert.AreEqual(byteArray[3], 0xff); Assert.AreEqual(BinaryUtils.ByteArrayToHex(byteArray), hex); } { //\t \n スペースは無視する byte[] byteArray = BinaryUtils.HexToByteArray("00\t\n01\n \tfe ff"); Assert.AreEqual(byteArray[0], 0); Assert.AreEqual(byteArray[1], 1); Assert.AreEqual(byteArray[2], 0xfe); Assert.AreEqual(byteArray[3], 0xff); Assert.AreEqual(BinaryUtils.ByteArrayToHex(byteArray), "00 01 fe ff"); } { byte[] byteArray = BinaryUtils.HexToByteArray(" \r \t \n "); Assert.AreEqual(byteArray.Length, 0); } { //例外発生パターン try { byte[] byteArray = BinaryUtils.HexToByteArray("w"); Assert.Fail(); } catch (Exception) { } } { //例外発生パターン try { byte[] byteArray = BinaryUtils.HexToByteArray("111"); Assert.Fail(); } catch (Exception) { } } } //HexToByteArrayTest()
public void ByteArrayToHexTest() { //基本的なテストは HexToByteArrayTest() で行っています。 { byte[] byteArray = new byte[0]; string hex = BinaryUtils.ByteArrayToHex(byteArray); Assert.AreEqual(hex.Length, 0); } { byte[] byteArray = null; string hex = BinaryUtils.ByteArrayToHex(byteArray); Assert.AreEqual(hex.Length, 0); } } //ByteArrayToHexTest()
IPlugin _plugin; //操作対象プラグイン。改行コードを持つプラグインの場合に、改行コードを取得するのに使用。 public StrToHexMenu(string text, IPlugin plugin, TextBoxEx textbox, Encoding encoding) { this.Text = text; _plugin = plugin; //文字列 -> 16進数 this.Click += (sender, e) => { try { //改行コードを変更します string newLineCode = "\r\n"; if (_plugin is INewLinePlugin) { newLineCode = ((INewLinePlugin)_plugin).NewLineCode; } string targetText = textbox.SelectedText.Replace("\n", newLineCode); byte[] byteArray = encoding.GetBytes(targetText); textbox.SelectionStart = textbox.SelectionStart + textbox.SelectionLength; textbox.SelectionLength = 0; textbox.SelectedText = " " + BinaryUtils.ByteArrayToHex(byteArray); } catch (Exception) { } }; }