private string getFiles(FileReader reader, DirectoryInfo dir) { StringBuilder sb = new StringBuilder(); try { foreach (FileInfo f in dir.GetFiles()) { //各ファイルの文字コード判別のみ実施し、StringBuilderに結果をタブ区切りで詰め込む CharCode c = reader.Read(f); sb.Append((f.DirectoryName + @"\").Substring(rootDir.Length)); sb.Append("\t"); sb.Append(f.Name); sb.Append("\t"); sb.Append(c.Name); sb.AppendLine(); } foreach (DirectoryInfo d in dir.GetDirectories()) { //サブフォルダについて再帰 sb.Append(getFiles(reader, d)); } } catch (UnauthorizedAccessException) { } return(sb.ToString()); }
private void button1_Click(object sender, EventArgs e) { //連続読み出しの最大許容ファイルサイズ指定値 int maxFileSize = (int)nmuMaxSize.Value; string path = txtPath.Text; if (File.Exists(path)) { //ファイル指定:単一ファイル読み出しの実行例 System.IO.FileInfo file = new FileInfo(path); using (FileReader reader = new FileReader(file)) { //コンボボックス選択どおりの文字コード判別オブジェクトで判別 reader.ReadJEnc = list[selDefault.SelectedIndex]; // (ReadJEnc)selDefault.SelectedItem; //判別結果の文字コードは、Readメソッドの戻り値で把握できます CharCode c = reader.Read(file); //戻り値の型からファイルの大まかな種類が判定できます、 string type = (c is CharCode.Text ? "Text:" : c is FileType.Bin ? "Binary:" : c is FileType.Image ? "Image:" : ""); //戻り値のNameプロパティから文字コード名を取得できます string name = c.Name; //戻り値のGetEncoding()メソッドで、エンコーディングを取得できます System.Text.Encoding enc = c.GetEncoding(); //実際に読み出したテキストは、Textプロパティから取得できます //(非テキストファイルの場合は、nullが設定されます) string text = reader.Text; txtResult.Text = "【" + type + c.Name + "】" + file.Name + "\r\n" + "-------------------------------------------" + "\r\n" + (text != null ? text : ""); btnClipboard.Enabled = true; } } else if (Directory.Exists(path)) { //ディレクトリ指定:複数ファイル連続読み出しの実行例 txtResult.Text = "一括判定中。。。"; txtResult.Refresh(); //最大許容ファイルサイズ指定でオブジェクトを作成する using (FileReader reader = new FileReader(maxFileSize)) { //コンボボックス選択どおりの文字コード判別オブジェクトで判別 reader.ReadJEnc = list[selDefault.SelectedIndex]; // (ReadJEnc)selDefault.SelectedItem; //ディレクトリ再帰調査 DirectoryInfo dir = new DirectoryInfo(path); rootDir = dir.FullName.TrimEnd('\\') + @"\"; txtResult.Text = getFiles(reader, dir); btnClipboard.Enabled = true; } } else { MessageBox.Show("ディレクトリまたはファイルのフルパスを指定してください。", "Path指定エラー", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary>バイト配列先頭のマジックナンバーよりバイナリファイル種類を判定する</summary> /// <param name="bytes">判定対象のバイト配列</param> /// <param name="Read">バイト配列先頭の読み込み済バイト数(LEASTREADSIZEのバイト数以上読み込んでおくこと)</param> /// <returns>バイナリファイル種類判定結果(どれにも該当しなければ一般バイナリと判定)</returns> public static CharCode GetBinaryType(byte[] bytes, int Read) { //定義済みマジックナンバーすべてを対象に一致判定 CharCode ret = GetPreamble(bytes, Read, BMP, GIF, JPEG, PNG, TIFF, IMGICON, JAVABIN, WINBIN, SHORTCUT, PDF, ZIP, GZIP, SEVENZIP, RAR, CABINET); //ファイル種類に応じた追加判定 if (ret == IMGICON && (Read < 23 || bytes[4] == 0 || bytes[5] != 0)) { ret = null; } //ICONの誤判別防止用(アイコン個数チェック) //判定できたファイル種類を返す(どれにも該当しなければ一般バイナリと判定) return(ret != null ? ret : BINARY); }
public SrtSubtitle LoadSrtSubtitle(string srtPath) { try { string characterCode = null; using (FileStream srtFileStream = File.OpenRead(srtPath)) { Ude.CharsetDetector detector = new Ude.CharsetDetector(); detector.Feed(srtFileStream); detector.DataEnd(); if (detector.Charset != null) { this.logger.Log($"Detected encoding {detector.Charset} for {srtPath} with confidence {detector.Confidence}."); characterCode = CharCode.FromUdeCode(detector.Charset); if (characterCode == null) { this.logger.Log("Detected encoding does not match with any available encoding."); } else { this.logger.Log("Picked encoding " + characterCode); } } if (characterCode == null) { StaticResolver.Resolve <IMessageBoxService>().Show(this, SubtitleRes.SubtitleCharsetDetectionFailedMessage); characterCode = "UTF-8"; } } return(new SrtSubtitle { FileName = srtPath, Default = false, CharacterCode = characterCode, LanguageCode = LanguageUtilities.GetDefaultLanguageCode(), Offset = 0 }); } catch (Exception exception) { this.logger.LogError("Could not load SRT file: " + exception); return(null); } }
/// <summary> /// Iniファイル読み込み /// </summary> /// <param name="iniFile"></param> public void Load(string iniFile) { FileInfo fi = new FileInfo(iniFile); if (fi.Length > 0) { using (FileReader fr = new FileReader(fi)) { CharCode code = fr.Read(fi); this.Encoding = code.GetEncoding().WebName; this.WithBOM = UTFCodes.Contains(code); ReadIniSection(fr.Text); } } else { this.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS").WebName; } }
/// <summary> /// トラックにテキストベースイベントを生成して挿入(文字コード指定あり) /// </summary> /// <param name="time">時刻</param> /// <param name="kind">イベントの種類</param> /// <param name="charCode">文字コード</param> /// <param name="text">テキスト</param> public void InsertTextBasedEvent(int time, Kind kind, CharCode charCode, string text) { if (kind <= 0x00 || (int)kind >= 0x1F) { throw new ArgumentException("テキストイベントではありません。", nameof(kind)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } /* lCharCode==MIDIEVENT_NOCHARCODEの場合でも、*/ /* 文字コードは直近の同種イベントに基づいてエンコードされるが、*/ /* この時点では探索ができないため、仮に空の文字列で生成する。 */ Event @event = Event.CreateTextBasedEvent(time, kind, charCode, ""); try { InsertEvent(@event); } catch (Exception ex) { @event.Delete(); throw; } /* トラックに挿入されているので、直近の同種イベントを探索できる。*/ /* lCharCode==MIDIEVENT_NOCHARCODEの場合、 * /* 文字コードは直近の同種イベントに基づきエンコードされる。 */ try { @event.Text = text; } catch (Exception ex) { RemoveEvent(@event); @event.Delete(); throw; } }
/// <summary> /// Sender側。スクリプトファイルを読み込んで格納する /// </summary> /// <param name="scriptFile"></param> public void LoadScript(string scriptFile) { this.ScriptName = Path.GetFileName(scriptFile); FileInfo fi = new FileInfo(scriptFile); if (fi.Length > 0) { using (var fr = new FileReader(fi)) { CharCode code = fr.Read(fi); this.Encoding = code.GetEncoding().WebName; this.WithBOM = UTFCodes.Contains(code); this.ScriptBody = fr.Text; } } else { this.Encoding = System.Text.Encoding.UTF8.WebName; this.WithBOM = true; } }
/// <summary> /// 生成验证码 /// </summary> /// <param name="type"></param> /// <param name="length"></param> public static void Render(ValidateCodeType type, int length) { string code = string.Empty; switch (type) { case ValidateCodeType.Char: { code = CharCode.GetRandomChar(length); break; } case ValidateCodeType.Chinese: { code = ChineseCode.GetChinese(length); break; } case ValidateCodeType.Num: { code = RandomStr.GetRandomNum(length); break; } } System.Web.HttpContext.Current.Session[CodeName] = code; ImagesHelper images = new ImagesHelper(); images.Width = 100; images.Height = 31; images.Text = code; images.LineNoise = ImagesHelper.LineNoiseLevel.Extreme; images.BackgroundNoise = ImagesHelper.BackgroundNoiseLevel.Extreme; images.FontWarp = ImagesHelper.FontWarpFactor.Extreme; images.CreateImage(); }
/// <summary> /// エンコードを自動判別してファイルを読み込みます /// </summary> /// <param name="fileName">ファイル名</param> /// <param name="text">読み込んだテキストデータ</param> /// <returns>読み込みに失敗、またはテキストファイルではないときfalse</returns> public static bool LoadTextByAnyEncoding(string fileName, out string text) { text = default(string); if (!File.Exists(fileName)) { return(false); } System.IO.FileInfo file = new FileInfo(fileName); using (FileReader reader = new FileReader(file)) { CharCode c = reader.Read(file); if (!(c is CharCode.Text)) { // テキストファイルじゃない return(false); } text = reader.Text; } return(true); }
static void Main(string[] args) { ReadOnlyCollection <string> OPTION_HAS_ARG = Array.AsReadOnly(new string[] { "e", "h", "t" }); List <string> path = new List <string>(); List <string> option = new List <string>(); List <string> script = new List <string>(); List <string> input = new List <string>(); List <string> patternSpace = new List <string>(); //var test = AddressText.TryParse("1,/bbb/"); //if (test.WasSuccessful) Console.WriteLine(test.Value); // args を 入力パス、オプション、スクリプトの3つに分ける。 if (args.Length != 0) { bool nextIsOption = false; //引数をオプション、パス、スクリプトの3つに分ける。 foreach (string arg in args) { if (arg.StartsWith("-")) { string op = arg.TrimStart("-".ToCharArray()).ToLower(); if (OPTION_HAS_ARG.Contains(op)) { nextIsOption = true; //次のargをオプションの引数とする。 } option.Add(op); } else if (nextIsOption) { if (arg.StartsWith("-")) { CautionDosentHaveArg(option); } option.Add(arg); nextIsOption = false; } else if (File.Exists(arg)) { path.Add(arg); } else if (IsScript(arg)) { script.Add(TrimSingleQuotation(arg)); } else { script.Add(arg); } } if (nextIsOption) { CautionDosentHaveArg(option); //オプションがないときは注意。 } // Encoding解釈(日本語:path[0]優先) Encoding enc = Encoding.GetEncoding("utf-8"); if (path.Count != 0) { FileInfo fi = new FileInfo(path[0]); using (FileReader fr = new FileReader(fi)) { //日本語優先でエンコード判別 fr.ReadJEnc = ReadJEnc.JP; CharCode cc = fr.Read(fi); //エンコード判別に成功したならエンコードを上書き var tmp = cc.GetEncoding(); if (tmp != null) { enc = tmp; } } } // option解釈(特殊編:returnするものは優先度順にこちらへ) if (option.Contains("d")) { TraceDebugData(path, option, script); #if DEBUG Console.ReadLine(); #endif return; } else if (option.Contains("v")) { DisplayVersion(); #if DEBUG Console.ReadLine(); #endif return; } bool silentMode = false; bool rulerMode = false; bool inplaceMode = false; int tail = -1; //tail引数。最終何行を読み出すか int head = -1; //head引数、頭何行を読み出すか // option解釈(普通編:逐次解釈するものはこちらへ) bool nextLoopSkip = false; foreach (string op in option.ToArray()) { if (nextLoopSkip) { nextLoopSkip = false; continue; } string opArg; // Option argment switch (op) { case "e": if (!string.IsNullOrEmpty(opArg = GetOptionArg(option, op))) { enc = Encoding.GetEncoding(opArg); } break; case "n": silentMode = true; break; case "r": rulerMode = true; break; case "I": ignoreCase = true; break; case "i": inplaceMode = true; break; case "t": if (!string.IsNullOrEmpty(opArg = GetOptionArg(option, op))) { tail = int.Parse(opArg); } break; case "h": if (!string.IsNullOrEmpty(opArg = GetOptionArg(option, op))) { head = int.Parse(opArg); } break; default: Console.WriteLine("{0} is illigall option! :-<", op); break; } if (OPTION_HAS_ARG.Contains(op)) { nextLoopSkip = true; //次はオプション引数なのでスキップ } } // OutputEncodingにUnicodeEncoding型を代入するとNG if (!(enc is UnicodeEncoding)) { Console.OutputEncoding = enc; } if (path.Count == 0) { //標準入力を入力としてコンソールに出力する ExtractInput(input, enc); ked(script, ref input, ref patternSpace, silentMode, rulerMode, tail, head); } else { foreach (string p in path.ToArray()) { //パスを入力として、inplaceModeによって出力先をファイルかコンソールか選ぶ ExtractInput(p, input, enc); ked(script, ref input, ref patternSpace, silentMode, rulerMode, inplaceMode, tail, head, p, enc); } } #if DEBUG Console.ReadLine(); #endif } else { CautionUsage(); } }
public override int GetHashCode() { return(Alt.GetHashCode() + CharCode.GetHashCode() + Control.GetHashCode() + Shift.GetHashCode()); }