→.NETプログラミング

#contents

*テキストファイルを読む [#e18b7578]
 using System.IO;
 public class TextFromFile 
 {
    private const string FILE_NAME = "MyFile.txt";
    public static void Main(String[] args) 
    {
        if (!File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} does not exist.", FILE_NAME);
            return;
        }
        using (StreamReader sr = File.OpenText(FILE_NAME))
        {
            String input;
            while ((input=sr.ReadLine())!=null) 
            {
                Console.WriteLine(input);
            }
            Console.WriteLine ("The end of the stream has been reached.");
            sr.Close();
        }
    }
 }

*ファイルサイズ取得 [#ya4f550d]
 System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
 //ファイルのサイズを取得
 long filesize = fi.Length;
-注意!FileInfoを取得した後に元のファイルを削除してしまうと、FileInfoの情報も参照できなくなるので注意されたし。

*ディスク空き容量の取得 [#z2d37c72]
-System.Management.ManagementObjectを使う方法とFileSystemObjectを使う方法がある
-ManagementObjectを使う場合
  static UInt64 GetDiskFreeSpace(String DriveLetter)
  {
    try
    {
      Debug.Assert(DriveLetter.Length == 1);
      ManagementObject mo = new ManagementObject("Win32_LogicalDisk=\"" + DriveLetter + ":\"");
      UInt64 rc = Convert.ToUInt64(mo.Properties["FreeSpace"].Value);  // 全容量なら "Size"
 
      return rc;
    }
    catch (Exception ex)
    {
      Debug.Fail(ex.Message);
      return 0;
    }
  }
-実行環境によってはManagementObjectはポリシーによって使用を禁止されている場合があることに注意されたし
-参考:[[FileSystemObjectについて>http://hanatyan.sakura.ne.jp/vbhlp/FSO01.htm]]
--[[指定されたドライブのディスク容量を取得>http://hanatyan.sakura.ne.jp/vbhlp/FSO02.htm]]


*ZIP書庫の作成、解凍 [#xf89266e]
-http://dobon.net/vb/dotnet/links/createzipfile.html
-J#用のDLLであるvjslib.dllを使う
-参考:http://msdn.microsoft.com/ja-jp/magazine/cc164129(en-us).aspx
-''注意!''J#用DLLであるvjslib.dllは環境によっては入っていないことがあるので注意されたし(普通に.NET Frameworkを入れただけでは入ってない?)
--対処法としては、セットアップを作るときに含まれるようにしておく。ClickOnceなら配布対象に含める。
--しかし、それでもダメな環境ではダメな模様。「Java.Lang.System 初期化子が例外をスローしました」というエラーになる。その場合はVisual J# 2.0再頒布パッケージをインストールする必要がある

**ZipEntry.getSize()で-1が返って来ることがある件 [#j1b3d0ab]
-どういうわけか上記のサンプルでZipEntryを取ってきてもgetSize()が-1を返してしまい、ファイルサイズが取得できないことがある。原因はよくわからないが、ZipOutputStreamを使って作ったzipファイルはそうなってしまう模様。

-対処法としては、ZipFileクラスを使って以下のように取得しなおすと取れる
 ZipFile zf = new ZipFile(zipFile); 
 //zippedFileNameはZipInputStream.getNextEntry()であらかじめ取得しておく
 ZipEntry ze2 = zf.getEntry(ZippedFileName);
 FileSize = ze2.getSize();
 CompressedFileSize = ze2.getCompressedSize();
 zf.close(); //closeするのを忘れないこと!
-参考URL:http://www.velocityreviews.com/forums/t126695-zipentrygetsize.html
-参考URL2:http://vimalathithen.blogspot.com/2006/06/using-zipentrygetsize.html
--ZipEntry.getSize() always returned -1 when the size of the zip entry was accessed. Digging around the net I found out the issue arises if the jar file was either compressed using ZipOutputStream or using the jar utility. The solution is to use ZipFile instead of ZipInputStream. The above code has to be altered as shown below to get the correct size.



*一時ファイル、Tmpファイル [#e0844c61]
-[[一時ファイル名、一時ディレクトリ名の取得>http://dobon.net/vb/dotnet/file/gettempfilename.html]]
--一時ファイル名は、System.IO.Path.GetTempFileNameで取得できます。
--フルパスで取得されます

*ファイルの列挙 [#gddfceea]
-System.IO.Directory.GetFiles()

*ファイルのコピー、削除、移動、属性操作 [#v6c1dfd3]
-[[SHFileOperationでやりたい場合のサンプル>http://uchukamen.com/Programming1/ToRecycleBin/#SEC5]]
-拡張子の変更
 Path.ChangeExtension()
-http://dobon.net/vb/dotnet/file/filecopy.html
-using System.IOして File.Copy()とか File.Delete()とか
-自前でバイナリファイルコピー
 FileStream fs_src = new FileStream(src, FileMode.Open, FileAccess.Read);
 FileStream fs_dst = new FileStream(dst, FileMode.OpenOrCreate, FileAccess.Write);
 byte[] buf = new byte[4096];
 int len;
 while ((len = fs_src.Read(buf, 0, buf.Length)) > 0)
 {
   fs_dst.Write(buf, 0, len);
 }
 fs_dst.Close();
 fs_src.Close();


*NTFSの機能で暗号化 [#ccc28231]
-http://www.atmarkit.co.jp/fdotnet/dotnettips/550fileencypt/fileencypt.html
 using System;
 using System.IO; 
 
 class Program
 {
   static void Main()
   {
     string path = @"C:\fdotnet\sample.txt";
     File.Encrypt(path);
   }
 }


*ファイル・フォルダの変更を監視 [#seeccb85]
-FileSystemWatcherというクラスがあるらしい
-http://dobon.net/vb/dotnet/file/filesystemwatcher.html

*ファイルの属性判定 [#oa992984]
-FileAttributes 型はビット演算できるように属性がセットされている(AttributeUsage属性をヘルプで参照)
-リードオンリー属性の判定例
 FileAttributes atr = File.GetAttributes(path);
 if( (atr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly ) 
 {
    //リードオンリーだったらやる処理を書く
 }

*非同期ファイルI/O [#da0f9c14]
-http://www.codeproject.com/useritems/asyncFileIO.asp

*パス文字列操作 [#l9659b27]
-パス文字列がフルパスかどうかの判定
--Path.IsPathRooted()を使う

-既存のファイルとかぶらないファイル名()数字付きを作る
 //引数はフルパスで来ることを想定
 protected String MakeUniqueFileName( String path ) 
 {
   String dir = Path.GetDirectoryName(path);
   String ext = Path.GetExtension(path);
   String fnwe =  Path.GetFileNameWithoutExtension(path);
 
   //ぶつからない名前になるまでまわす
   int num = 1;
   String newName ;
   do
   {
     newName = dir + "\\" + fnwe + "(" + num + ")" + ext;
     num++;
   }
   while(File.Exists(newName ));
 
   return newName;
 }

-[[一時ファイル用のランダムなファイル名を作る>http://www.atmarkit.co.jp/fdotnet/dotnettips/554randomfilename/randomfilename.html]]

*ファイル操作 [#ccfa30d7]
-テキスト書き込み
--FileStreamクラスを使用
--http://dobon.net/vb/dotnet/file/writefile.html

-テキスト読み込み
 StreamReader sr = new StreamReader(path, Encoding.Default);
 
 String s = sr.ReadLine();
 while(s != null)
 {
     //処理をする
 }
 sr.Close();


-存在チェック
--File.Exists()を使う

*各種フォルダ取得 [#v8582b32]
-参考:http://dobon.net/vb/dotnet/file/getfolderpath.html
-[[参考:特殊フォルダのOS毎の違い:http://santamartadotnet.hp.infoseek.co.jp/documents/dotnet/diffofspecialfolders.html]]

**デスクトップフォルダ取得 [#a023b400]
 System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
または
 System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory);
この二つの違いは、上が仮想フォルダで下が物理フォルダとのことなのだが、実際に試すと同じ結果になるようで、正直よくわからない

**My Document [#fa89c7ed]
 System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

**Tempフォルダのパス取得 [#v5240e8c]
 Path.GetTempPath()
-http://www.atmarkit.co.jp/fdotnet/dotnettips/230tempdir/tempdir.html

**カレントディレクトリ取得 [#e3521f9c]
 string stCurrentDir = System.IO.Directory.GetCurrentDirectory();
--カレントディレクトリ=Exeのあるフォルダ''とは限らない''点に注意

**実行ファイルのPath取得 [#kcee9486]
-方法1
 System.Windows.Forms.Application.StartupPath を参照
--ファイル名を含まない

-方法2
 string s = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]).FullyQualifiedName;
 //もしくは
 string s = System.Reflection.Assembly.GetExecutingAssembly().Location
これはファイル名まで返す点に注意。フォルダ名だけが欲しい場合はPath.GetDirectoryName()をかます。

-方法3
 string appPath = Application.ExecutablePath;
これもファイル名まで含みます

**DLLのPath取得 [#k4a214ee]
 string m_Path = Assembly.GetExecutingAssembly().CodeBase ;
 string m_Dir = System.IO.Path.GetDirectoryName(m_Path);

これ↓だとキャッシュディレクトリが返る
 path = this.GetType().Module.FullyQualifiedName;


*CSV処理 [#db33caa8]
-[[Fast CSV Reader:http://www.codeproject.com/cs/database/CsvReader.asp]]
--String.Split()で処理できないようなCSVでも扱える。データ中に「,」があるとか
--サンプル
 //ヘッダ行なしの場合
 CsvReader csv =new CsvReader(new StreamReader(FileName,Encoding.Default), false);
 while(csv.ReadNextRecord())
 {
   String fld1 = csv[0];
   String fld2 = csv[1];
   ...(適当になにかやる)
 }
--注意点:コンストラクタに渡すStreamReaderにはちゃんとエンコーディングを渡しておかないと漢字を正しく処理できないので注意(これはCsvReaderの問題ではない)

-[[.NETでのCSVファイルの操作:http://www.codeproject.com/cs/database/FinalCSVReader.asp]]
--ODBCのText Driverを使っている模様

トップ   編集 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS