C#編程-110:文件操作File靜態類
using?System;
using?System.Collections.Generic;
using?System.Linq;
using?System.Text;
using?System.IO;
namespace?IOTest
{
class?Program
{
static?void?Main(string[]?args)
{
//判斷文件是否存在
//file是靜態類
string?path?=?@"C:\Users\pengshiyu\Desktop\新建文本文檔.txt";
if?(File.Exists(path))?Console.WriteLine("file?\""+path+"\"?is?exists");
else?Console.WriteLine("file?\""+path+"\"?is?not?exists");
//創建文件,注意:需要把創建的文件流關閉
//方法一:try?catch語句
//方法二:先判斷不存在,再創建
string?path1?=?@"C:\Users\pengshiyu\Desktop\";
if?(!File.Exists(path1?+?"newFile.txt"))
{
FileStream?filestream?=?File.Create(path1?+?"newFile.txt");
filestream.Close();
Console.WriteLine("文件創建成功!");
}
else
Console.WriteLine("文件已經存在!");
//打開文件
//FileMode有六種枚舉
string?path2?=?@"C:\Users\pengshiyu\Desktop\test.txt";
try
{
FileStream?filestream?=?File.Open(path2,FileMode.Truncate);
byte[]?writebyte?=?{?(byte)'p',?(byte)'s',?(byte)'y',?(byte)',',?(byte)'t',?(byte)'e',?(byte)'s',?(byte)'t'?};
filestream.Write(writebyte,0,writebyte.Length);
filestream.Close();
Console.WriteLine("文件寫入成功!");
}
catch?(Exception?ex)
{
Console.WriteLine(ex.Message);
}
//文件復制
string?pathSource?=?@"C:\Users\pengshiyu\Desktop\source\test.txt";
string?pathDestination?=?@"C:\Users\pengshiyu\Desktop\destination\test.txt";
if?(File.Exists(pathSource))
{
try
{
if?(!File.Exists(pathDestination))
{
Console.WriteLine("請選擇復制(1)還是移動(2):");
string?choice?=?Console.ReadLine();
if?(choice?==?"1")
{
//文件復制
File.Copy(pathSource,?pathDestination,?false);
Console.WriteLine("文件拷貝成功!");
Console.WriteLine("是否刪除源文件?刪除:1,不刪除:2");
string?delChoice?=?Console.ReadLine();
if?(delChoice?==?"1")
{
//文件刪除
File.Delete(pathSource);
Console.WriteLine("源文件刪除成功!");
}
else?if?(delChoice?==?"2")
{
Console.WriteLine("不刪除!");
}
else
{
Console.WriteLine("用戶輸入有誤!");
}
}
else?if?(choice?==?"2")
{
//文件移動
File.Move(pathSource,?pathDestination);
Console.WriteLine("文件移動成功!");
}
else
{
Console.WriteLine("文件存在,是否覆蓋?是:1,否:2");
string?choicecover?=?Console.ReadLine();
if?(choicecover?==?"1")
{
File.Copy(pathSource,?pathDestination,?true);
Console.WriteLine("文件拷貝成功,覆蓋完成!");
}
else?if?(choicecover?==?"2")
{
Console.WriteLine("文件拷貝失敗,文件已存在!");
}
else
{
Console.WriteLine("輸入有誤!");
}
}
}
}
catch?(Exception?ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
Console.WriteLine("源文件不存在");
}
Console.ReadKey();
}
}
}
C#
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。