獲取文件的版本信息:
fileversioninfo myfileversioninfo1 = fileversioninfo.getversioninfo("d://test.dll");
textbox1.text="版本號(hào): " + myfileversioninfo1.fileversion;
更改文件屬性,刪除只讀文件:
下例欲將e:/test.txt文件拷貝至d:/tmp/test.txt,但d:/tmp/test.txt已經(jīng)存在。
//file.copy(sourcefile,destinationfile,true); 用來(lái)拷貝文件
//當(dāng)destinationfile已經(jīng)存在時(shí),無(wú)法將文件file1拷貝到目標(biāo)文件,
//因此先刪除destination文件,file.delete()方法不能刪除只讀文件,
//因此,如果文件屬性為只讀(attributes屬性中會(huì)包含有"readonly"),
//先把文件屬性重置為normal,然后再刪除:
string file1="e://test.txt";
string destinationfile="d://tmp//test.txt";
if(file.exists(destinationfile))
{
fileinfo fi=new fileinfo(destinationfile);
if(fi.attributes.tostring().indexof("readonly")!=-1)
fi.attributes=fileattributes.normal;
file.delete(destinationfile);
}
file.copy(file1,destinationfile,true);
判斷文件是否存在:file.exists(string filepath)
判斷目錄是否存在:directory.exists("d://lastestversion")
按行讀取文件:
int filecount=0;
// open the file just specified such that no one else can use it.
streamreader sr = new streamreader(textbox1.text.trim());
while(sr.peek() > -1)//streamreader.peek()返回下一個(gè)可用字符,但不使用它
{
listbox1.items.add(sr.readline());
filecount++;
}
sr.close();
按行寫(xiě)入文件:
streamwriter sw = new streamwriter("d://result.txt");
for(int i=0;i<10;i++)
{
sw.writeline("這是第"+i.tostring()+"行數(shù)據(jù)");
}
方法二:
private const int fo_delete = 0x3;
private const ushort fof_noconfirmation = 0x10;
private const ushort fof_allowundo = 0x40;
[dllimport("shell32.dll", setlasterror=true, charset=charset.unicode)]
private static extern int shfileoperation([in,out] _shfileopstruct str);
[structlayout(layoutkind.sequential, charset=charset.unicode)]
public class _shfileopstruct
{
public intptr hwnd;
public uint32 wfunc;
public string pfrom;
public string pto;
public uint16 fflags;
public int32 fanyoperationsaborted;
public intptr hnamemappings;
public string lpszprogresstitle;
}
public static int delete(string path)
{
_shfileopstruct pm = new _shfileopstruct();
pm.wfunc = fo_delete;
pm.pfrom = path + '/0';
pm.pto = null;
pm.fflags = fof_allowundo ¦ fof_noconfirmation;
return shfileoperation(pm);
}
調(diào)用:class1.delete("c://temp.txt");
注:返回值為0表示調(diào)用成功,非0表示調(diào)用失敗。
需要引用system.runtime.interopservices命名空間。
新聞熱點(diǎn)
疑難解答
圖片精選