0
0

More than 5 years have passed since last update.

Visual Studio | WPF > fileIO > ファイルのコピー (上書きあり|上書きなし) > System.IO.Fileクラス使用

Last updated at Posted at 2017-11-15
動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

ファイルのコピー方法に関して。

参考

二つ目のFile.Copy()はoverwriteを指定できる。

code

MainWindow.xaml
<Window x:Class="_171115_t0940_filecopy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_171115_t0940_filecopy"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Name="B_filecopy" Height="30" Content="file copy" Click="B_filecopy_Click"/>
    </Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// 以下を追加
using System.IO;

namespace _171115_t0940_filecopy
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly string kFromFile = "D:\\FileProcess_171115\\171010.csv";
        private readonly string kToFile = "D:\\FileProcess_171115\\171015.csv";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void copyFile_noOverwrite()
        {
            try
            {
                File.Copy(kFromFile, kToFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString()); // (1)
            }
        }

        private void copyFile_overwrite()
        {
            try
            {
                File.Copy(kFromFile, kToFile, overwrite: true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString()); // (2)
            }
        }

        private void B_filecopy_Click(object sender, RoutedEventArgs e)
        {
            copyFile_overwrite();
            copyFile_noOverwrite();
        }
    }
}

File.Copy(String, String)実行時にファイルが既存するためにエラーが出る。

qiita.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0