C#编程-110:文件操作File静态类_彭世瑜_新浪博客
【摘要】
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace IOTest { cla...
- 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();
- }
- }
- }
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/109661863
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)