.NET ファイルシステム関連
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
検索
|
最終更新
|
ヘルプ
|
ログイン
] [
Twitter
]
開始行:
→.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...
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...
sr.Close();
}
}
}
*ファイルサイズ取得 [#ya4f550d]
System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
//ファイルのサイズを取得
long filesize = fi.Length;
-注意!FileInfoを取得した後に元のファイルを削除してしまう...
*ディスク空き容量の取得 [#z2d37c72]
-System.Management.ManagementObjectを使う方法とFileSystem...
-ManagementObjectを使う場合
static UInt64 GetDiskFreeSpace(String DriveLetter)
{
try
{
Debug.Assert(DriveLetter.Length == 1);
ManagementObject mo = new ManagementObject("Win32_L...
UInt64 rc = Convert.ToUInt64(mo.Properties["FreeSpa...
return rc;
}
catch (Exception ex)
{
Debug.Fail(ex.Message);
return 0;
}
}
-実行環境によってはManagementObjectはポリシーによって使用...
-参考:[[FileSystemObjectについて>http://hanatyan.sakura....
--[[指定されたドライブのディスク容量を取得>http://hanatya...
*ZIP書庫の作成、解凍 [#xf89266e]
-http://dobon.net/vb/dotnet/links/createzipfile.html
-J#用のDLLであるvjslib.dllを使う
-参考:http://msdn.microsoft.com/ja-jp/magazine/cc164129(...
-''注意!''J#用DLLであるvjslib.dllは環境によっては入って...
--対処法としては、セットアップを作るときに含まれるように...
--しかし、それでもダメな環境ではダメな模様。「Java.Lang.S...
**ZipEntry.getSize()で-1が返って来ることがある件 [#j1b3d0...
-どういうわけか上記のサンプルでZipEntryを取ってきてもgetS...
-対処法としては、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-zi...
-参考URL2:http://vimalathithen.blogspot.com/2006/06/using...
--ZipEntry.getSize() always returned -1 when the size of ...
*一時ファイル、Tmpファイル [#e0844c61]
-[[一時ファイル名、一時ディレクトリ名の取得>http://dobon....
--一時ファイル名は、System.IO.Path.GetTempFileNameで取得...
--フルパスで取得されます
*ファイルの列挙 [#gddfceea]
-System.IO.Directory.GetFiles()
*ファイルのコピー、削除、移動、属性操作 [#v6c1dfd3]
-[[SHFileOperationでやりたい場合のサンプル>http://uchukam...
-拡張子の変更
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, F...
FileStream fs_dst = new FileStream(dst, FileMode.OpenOrC...
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/550fileency...
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 型はビット演算できるように属性がセットさ...
-リードオンリー属性の判定例
FileAttributes atr = File.GetAttributes(path);
if( (atr & FileAttributes.ReadOnly) == FileAttributes.Re...
{
//リードオンリーだったらやる処理を書く
}
*非同期ファイル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....
*ファイル操作 [#ccfa30d7]
-テキスト書き込み
--FileStreamクラスを使用
--http://dobon.net/vb/dotnet/file/writefile.html
-テキスト読み込み
StreamReader sr = new StreamReader(path, Encoding.Defaul...
String s = sr.ReadLine();
while(s != null)
{
//処理をする
}
sr.Close();
-存在チェック
--File.Exists()を使う
*各種フォルダ取得 [#v8582b32]
-参考:http://dobon.net/vb/dotnet/file/getfolderpath.html
-[[参考:特殊フォルダのOS毎の違い:http://santamartadotnet...
**デスクトップフォルダ取得 [#a023b400]
System.Environment.GetFolderPath(System.Environment.Spec...
または
System.Environment.GetFolderPath(System.Environment.Spec...
この二つの違いは、上が仮想フォルダで下が物理フォルダとの...
**My Document [#fa89c7ed]
System.Environment.GetFolderPath(System.Environment.Spec...
**Tempフォルダのパス取得 [#v5240e8c]
Path.GetTempPath()
-http://www.atmarkit.co.jp/fdotnet/dotnettips/230tempdir/...
**カレントディレクトリ取得 [#e3521f9c]
string stCurrentDir = System.IO.Directory.GetCurrentDire...
--カレントディレクトリ=Exeのあるフォルダ''とは限らない''...
**実行ファイルのPath取得 [#kcee9486]
-方法1
System.Windows.Forms.Application.StartupPath を参照
--ファイル名を含まない
-方法2
string s = System.Reflection.Assembly.GetExecutingAssemb...
//もしくは
string s = System.Reflection.Assembly.GetExecutingAssemb...
これはファイル名まで返す点に注意。フォルダ名だけが欲しい...
-方法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...
--String.Split()で処理できないようなCSVでも扱える。データ...
--サンプル
//ヘッダ行なしの場合
CsvReader csv =new CsvReader(new StreamReader(FileName,E...
while(csv.ReadNextRecord())
{
String fld1 = csv[0];
String fld2 = csv[1];
...(適当になにかやる)
}
--注意点:コンストラクタに渡すStreamReaderにはちゃんとエ...
-[[.NETでのCSVファイルの操作:http://www.codeproject.com/c...
--ODBCのText Driverを使っている模様
終了行:
→.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...
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...
sr.Close();
}
}
}
*ファイルサイズ取得 [#ya4f550d]
System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
//ファイルのサイズを取得
long filesize = fi.Length;
-注意!FileInfoを取得した後に元のファイルを削除してしまう...
*ディスク空き容量の取得 [#z2d37c72]
-System.Management.ManagementObjectを使う方法とFileSystem...
-ManagementObjectを使う場合
static UInt64 GetDiskFreeSpace(String DriveLetter)
{
try
{
Debug.Assert(DriveLetter.Length == 1);
ManagementObject mo = new ManagementObject("Win32_L...
UInt64 rc = Convert.ToUInt64(mo.Properties["FreeSpa...
return rc;
}
catch (Exception ex)
{
Debug.Fail(ex.Message);
return 0;
}
}
-実行環境によってはManagementObjectはポリシーによって使用...
-参考:[[FileSystemObjectについて>http://hanatyan.sakura....
--[[指定されたドライブのディスク容量を取得>http://hanatya...
*ZIP書庫の作成、解凍 [#xf89266e]
-http://dobon.net/vb/dotnet/links/createzipfile.html
-J#用のDLLであるvjslib.dllを使う
-参考:http://msdn.microsoft.com/ja-jp/magazine/cc164129(...
-''注意!''J#用DLLであるvjslib.dllは環境によっては入って...
--対処法としては、セットアップを作るときに含まれるように...
--しかし、それでもダメな環境ではダメな模様。「Java.Lang.S...
**ZipEntry.getSize()で-1が返って来ることがある件 [#j1b3d0...
-どういうわけか上記のサンプルでZipEntryを取ってきてもgetS...
-対処法としては、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-zi...
-参考URL2:http://vimalathithen.blogspot.com/2006/06/using...
--ZipEntry.getSize() always returned -1 when the size of ...
*一時ファイル、Tmpファイル [#e0844c61]
-[[一時ファイル名、一時ディレクトリ名の取得>http://dobon....
--一時ファイル名は、System.IO.Path.GetTempFileNameで取得...
--フルパスで取得されます
*ファイルの列挙 [#gddfceea]
-System.IO.Directory.GetFiles()
*ファイルのコピー、削除、移動、属性操作 [#v6c1dfd3]
-[[SHFileOperationでやりたい場合のサンプル>http://uchukam...
-拡張子の変更
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, F...
FileStream fs_dst = new FileStream(dst, FileMode.OpenOrC...
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/550fileency...
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 型はビット演算できるように属性がセットさ...
-リードオンリー属性の判定例
FileAttributes atr = File.GetAttributes(path);
if( (atr & FileAttributes.ReadOnly) == FileAttributes.Re...
{
//リードオンリーだったらやる処理を書く
}
*非同期ファイル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....
*ファイル操作 [#ccfa30d7]
-テキスト書き込み
--FileStreamクラスを使用
--http://dobon.net/vb/dotnet/file/writefile.html
-テキスト読み込み
StreamReader sr = new StreamReader(path, Encoding.Defaul...
String s = sr.ReadLine();
while(s != null)
{
//処理をする
}
sr.Close();
-存在チェック
--File.Exists()を使う
*各種フォルダ取得 [#v8582b32]
-参考:http://dobon.net/vb/dotnet/file/getfolderpath.html
-[[参考:特殊フォルダのOS毎の違い:http://santamartadotnet...
**デスクトップフォルダ取得 [#a023b400]
System.Environment.GetFolderPath(System.Environment.Spec...
または
System.Environment.GetFolderPath(System.Environment.Spec...
この二つの違いは、上が仮想フォルダで下が物理フォルダとの...
**My Document [#fa89c7ed]
System.Environment.GetFolderPath(System.Environment.Spec...
**Tempフォルダのパス取得 [#v5240e8c]
Path.GetTempPath()
-http://www.atmarkit.co.jp/fdotnet/dotnettips/230tempdir/...
**カレントディレクトリ取得 [#e3521f9c]
string stCurrentDir = System.IO.Directory.GetCurrentDire...
--カレントディレクトリ=Exeのあるフォルダ''とは限らない''...
**実行ファイルのPath取得 [#kcee9486]
-方法1
System.Windows.Forms.Application.StartupPath を参照
--ファイル名を含まない
-方法2
string s = System.Reflection.Assembly.GetExecutingAssemb...
//もしくは
string s = System.Reflection.Assembly.GetExecutingAssemb...
これはファイル名まで返す点に注意。フォルダ名だけが欲しい...
-方法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...
--String.Split()で処理できないようなCSVでも扱える。データ...
--サンプル
//ヘッダ行なしの場合
CsvReader csv =new CsvReader(new StreamReader(FileName,E...
while(csv.ReadNextRecord())
{
String fld1 = csv[0];
String fld2 = csv[1];
...(適当になにかやる)
}
--注意点:コンストラクタに渡すStreamReaderにはちゃんとエ...
-[[.NETでのCSVファイルの操作:http://www.codeproject.com/c...
--ODBCのText Driverを使っている模様
ページ名: