Home >Backend Development >C#.Net Tutorial >How to copy and delete files in C#

How to copy and delete files in C#

黄舟
黄舟Original
2017-10-09 10:43:361718browse

这篇文章主要介绍了C# 复制与删除文件的实现方法的相关资料,希望通过本文能帮助到大家,让大家理解掌握这部分内容,需要的朋友可以参考下

C# 复制与删除文件的实现方法

1、首先是复制文件

首先打开我们的对话框获得文件路径,当然也可以直接编写路径


private void BtnAddFile_Click(object sender, RoutedEventArgs e) 
  { 
   OpenFileDialog openFileDialog = new OpenFileDialog(); 
   if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
   { 
    string path = openFileDialog.FileName; 
    // System.Windows.Forms.MessageBox.Show(path); 
    MyFile.addFile(path); 
   } 
  }

然后是复制文件的方法买这里我写的是添加,是根据我的项目来的

MyFile是一个文件操作类,OpenFileDialog需要添加引用


public static void addFile(string path)  
    { 
      string[] s = path.Split('\\'); 
 
      try 
      { 
        File.Copy(path, "E:\\Share\\"+s[s.Length-1], true);  

     //path是你要复制的文件,第二个是目标路径,注意要获得文件名      
  } 
  catch (Exception ex)  
  { 
    System.Windows.Forms.MessageBox.Show(ex.Message); 
  } 
}

string[] s = path.Split("\\");这是一个分割字符串的方式,我们需要获得文件名,然后拼接成目标路径,我们是不能直接复制文件到文件夹中的

2、删除


public static void deleteFile(string path) 
  { 
   if (System.IO.File.Exists(path)) 
   { 
    try 
    { 
     System.IO.File.Delete(path); 
    } 
    catch (System.IO.IOException e) 
    { 
     Console.WriteLine(e.Message); 
     return; 
    } 
   } 
  }

The above is the detailed content of How to copy and delete files in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn