FileInfo.MoveTo 메서드

정의

오버로드

MoveTo(String)

지정된 파일을 새 위치로 이동하고 새 파일의 이름을 지정할 수 있는 옵션을 제공합니다.

MoveTo(String, Boolean)

새 파일 이름을 지정하고 대상 파일이 이미 있으면 덮어쓰는 옵션을 제공하여, 지정된 파일을 새 위치로 이동합니다.

MoveTo(String)

지정된 파일을 새 위치로 이동하고 새 파일의 이름을 지정할 수 있는 옵션을 제공합니다.

public:
 void MoveTo(System::String ^ destFileName);
public void MoveTo (string destFileName);
member this.MoveTo : string -> unit
Public Sub MoveTo (destFileName As String)

매개 변수

destFileName
String

파일을 이동할 경로입니다. 이 경로에서 다른 파일 이름을 지정할 수 있습니다.

예외

대상 파일이 이미 있거나 대상 디바이스가 준비되지 않은 것과 같은 I/O 오류가 발생합니다.

destFileName이(가) null인 경우

2.1 이전의 .NET Framework 및 .NET Core 버전: destFileName 비어 있거나 공백만 포함하거나 잘못된 문자를 포함합니다.

호출자에게 필요한 권한이 없는 경우

destFileName 가 읽기 전용이거나 디렉터리입니다.

파일을 찾을 수 없습니다.

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

destFileName의 문자열 중간에 콜론(:)이 있습니다.

예제

다음 예제에서는 파일을 다른 위치로 이동하고 파일 이름을 바꾸는 방법을 보여 줍니다.


using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace Microsoft.Samples.MoveTo.CS
{

    class Program
    {
        private static string sourcePath = Environment.GetFolderPath
            (Environment.SpecialFolder.MyDocuments) +
            @"\FileInfoTestDirectory\MoveFrom\FromFile.xml";
        
        private static string destPath = Environment.GetFolderPath
            (Environment.SpecialFolder.MyDocuments) +
            @"\FileInfoTestDirectory\DestFile.xml";
        //
        // The main entry point for the application.
        //
        [STAThread()] static void Main ()
        {
            // Change Console properties to make it obvious that
            // the application is starting.
            Console.Clear();
            // Move it to the upper left corner of the screen.
            Console.SetWindowPosition(0, 0);
            // Make it very large.
            Console.SetWindowSize(Console.LargestWindowWidth - 24,
                Console.LargestWindowHeight - 16);
            Console.WriteLine("Welcome.");
            Console.WriteLine("This application demonstrates the FileInfo.MoveTo method.");
            Console.WriteLine("Press any key to start.");
            string s = Console.ReadLine();
            Console.Write("    Checking whether ");
            Console.Write(sourcePath);
            Console.WriteLine(" exists.");
            FileInfo fInfo = new FileInfo (sourcePath);
            EnsureSourceFileExists();
            DisplayFileProperties(fInfo);
            Console.WriteLine("Preparing to move the file to ");
            Console.Write(destPath);
            Console.WriteLine(".");
            MoveFile(fInfo);
            DisplayFileProperties(fInfo);
            Console.WriteLine("Preparing to delete directories.");
            DeleteFiles();
            Console.WriteLine("Press the ENTER key to close this application.");
            s = Console.ReadLine();
        }
        //
        // Moves the supplied FileInfo instance to destPath.
        //
        private static void MoveFile(FileInfo fInfo)
        {
            try
            {
                fInfo.MoveTo(destPath);
                Console.WriteLine("File moved to ");
                Console.WriteLine(destPath);
            } catch (Exception ex) {
                DisplayException(ex);
            }
        }
        //
        // Ensures that the test directories
        // and the file FromFile.xml all exist.
        //
        private static void EnsureSourceFileExists()
        {
            FileInfo fInfo = new FileInfo(sourcePath);
            string dirPath = fInfo.Directory.FullName;
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            if (File.Exists(destPath))
            {
                File.Delete(destPath);
            }
            Console.Write("Creating file ");
            Console.Write(fInfo.FullName);
            Console.WriteLine(".");
            try
            {
                if (!fInfo.Exists)
                {
                    Console.WriteLine("Adding data to the file.");
                    WriteFileContent(10);
                    Console.WriteLine("Successfully created the file.");
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
            finally
            {
                dirPath = null;
            }
        }
        //
        // Creates and saves an Xml file to sourcePath.
        //
        private static void WriteFileContent(int totalElements)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, "yes"));
            doc.AppendChild(doc.CreateWhitespace("\r\n"));
            XmlElement root = doc.CreateElement("FileInfo.MoveTo");
            root.AppendChild(doc.CreateWhitespace("\r\n"));
            int index = 0;
            XmlElement elem;
            while (index < totalElements)
            {
                
                elem = doc.CreateElement("MyElement");
                elem.SetAttribute("Index", index.ToString());
                elem.AppendChild(doc.CreateWhitespace("\r\n"));
                elem.AppendChild(doc.CreateTextNode(String.Format
                    ("MyElement at position {0}.", index)));
                elem.AppendChild(doc.CreateWhitespace("\r\n"));
                root.AppendChild(elem);
                root.AppendChild(doc.CreateWhitespace("\r\n"));
                index++;
            }
            doc.AppendChild(root);
            doc.AppendChild(doc.CreateWhitespace("\r\n"));
            doc.Save(sourcePath);
            elem = null;
            root = null;
            doc = null;
        }
        //
        // Displays FullName, CreationTime, and LastWriteTime of the supplied
        // FileInfo instance, then displays the text of the file.
        //
        private static void DisplayFileProperties(FileInfo fInfo)
        {
            Console.WriteLine("The FileInfo instance shows these property values.");
            StreamReader reader = null;
            try
            {
                Console.Write("FullName: ");
                Console.WriteLine(fInfo.FullName);
                Console.Write("CreationTime: ");
                Console.WriteLine(fInfo.CreationTime);
                Console.Write("LastWriteTime: ");
                Console.WriteLine(fInfo.LastWriteTime);
                Console.WriteLine();
                Console.WriteLine("File contents:");
                Console.WriteLine();
                reader = new StreamReader(fInfo.FullName);
                while (!reader.EndOfStream)
                {
                    Console.WriteLine(reader.ReadLine());
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                reader = null;
            }
        }
        //
        // Deletes the test directory and all its files and subdirectories.
        //
        private static void DeleteFiles()
        {
            try
            {
                DirectoryInfo dInfo = new DirectoryInfo(Environment.GetFolderPath
                    (Environment.SpecialFolder.MyDocuments) + "\\FileInfoTestDirectory");
                if (dInfo.Exists)
                {
                    dInfo.Delete(true);
                    Console.WriteLine("Successfully deleted directories and files.");
                }
                dInfo = null;
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
        //
        // Displays information about the supplied Exception. This
        // code is not suitable for production applications.
        //
        private static void DisplayException(Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("An exception of type \"");
            sb.Append(ex.GetType().FullName);
            sb.Append("\" has occurred.\r\n");
            sb.Append(ex.Message);
            sb.Append("\r\nStack trace information:\r\n");
            MatchCollection matchCol = Regex.Matches(ex.StackTrace,
@"(at\s)(.+)(\.)([^\.]*)(\()([^\)]*)(\))((\sin\s)(.+)(:line )([\d]*))?");
            int L = matchCol.Count;
            string[] argList;
            Match matchObj;
            int y, K;
            for(int x = 0; x < L; x++)
            {
                matchObj = matchCol[x];
                sb.Append(matchObj.Result("\r\n\r\n$1 $2$3$4$5"));
                argList = matchObj.Groups[6].Value.Split(new char[] { ',' });
                K = argList.Length;
                for (y = 0; y < K; y++)
                {
                    sb.Append("\r\n    ");
                    sb.Append(argList[y].Trim().Replace(" ", "        "));
                    sb.Append(',');
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("\r\n)");
                if (0 < matchObj.Groups[8].Length)
                {
                    sb.Append(matchObj.Result("\r\n$10\r\nline $12"));
                }
            }
            argList = null;
            matchObj = null;
            matchCol = null;
            Console.WriteLine(sb.ToString());
            sb = null;
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
// Welcome.
// This application demonstrates the FileInfo.MoveTo method.
// Press any key to start.
//
//     Checking whether C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml exists.
// Creating file C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml.
// Adding data to the file.
// Successfully created the file.
// The FileInfo instance shows these property values.
// FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.

// Preparing to move the file to
// C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml.
// File moved to
// C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml
// The FileInfo instance shows these property values.
// FullName: C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
//
// Preparing to delete directories.
// Successfully deleted directories and files.
// Press the ENTER key to close this application.
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Xml

Module Program

    Private sourcePath As String = Environment.GetFolderPath _
    (Environment.SpecialFolder.MyDocuments) & _
    "\FileInfoTestDirectory\MoveFrom\FromFile.xml"
    '
    Private destPath As String = Environment.GetFolderPath _
    (Environment.SpecialFolder.MyDocuments) & _
    "\FileInfoTestDirectory\DestFile.xml"
    '
    ' The main entry point for the application.
    '
    <STAThread()> Sub Main()
        ' Change Console properties to make it obvious that 
        ' the application is starting.
        Console.Clear()
        ' Move it to the upper left corner of the screen.
        Console.SetWindowPosition(0, 0)
        ' Make it very large.
        Console.SetWindowSize(Console.LargestWindowWidth - 24, _
            Console.LargestWindowHeight - 16)
        Console.WriteLine("Welcome.")
        Console.WriteLine("This application demonstrates the FileInfo.MoveTo method.")
        Console.WriteLine("Press any key to start.")
        Dim s As String = Console.ReadLine()
        Console.Write("    Checking whether ")
        Console.Write(sourcePath)
        Console.WriteLine(" exists.")
        Dim fInfo As FileInfo = New FileInfo(sourcePath)
        EnsureSourceFileExists()
        DisplayFileProperties(fInfo)
        Console.WriteLine("Preparing to move the file to ")
        Console.Write(destPath)
        Console.WriteLine(".")
        MoveFile(fInfo)
        DisplayFileProperties(fInfo)
        Console.WriteLine("Preparing to delete directories.")
        DeleteFiles()
        Console.WriteLine("Press the ENTER key to close this application.")
        s = Console.ReadLine()
    End Sub
    '
    ' Moves the supplied FileInfo instance to destPath.
    '
    Private Sub MoveFile(ByVal fInfo As FileInfo)
        Try
            fInfo.MoveTo(destPath)
            Console.WriteLine("File moved to ")
            Console.WriteLine(destPath)
        Catch ex As Exception
            DisplayException(ex)
        End Try
    End Sub
    '
    ' Ensures that the test directories 
    ' and the file FromFile.xml all exist.
    '
    Private Sub EnsureSourceFileExists()
        ' Create a FileInfo instance, and get the full path 
        ' to the parent directory.
        Dim fInfo As FileInfo = New FileInfo(sourcePath)
        Dim dirPath As String = fInfo.Directory.FullName
        ' If the directory does not exist, create it.
        If Not Directory.Exists(dirPath) Then
            Directory.CreateDirectory(dirPath)
        End If
        ' If DestFile.xml exists, delete it.
        If File.Exists(destPath) Then
            File.Delete(destPath)
        End If
        Console.Write("Creating file ")
        Console.Write(fInfo.FullName)
        Console.WriteLine(".")
        Try
            If Not fInfo.Exists Then
                ' Call WriteFileContent to create the file.
                Console.WriteLine("Adding data to the file.")
                WriteFileContent(10)
                Console.WriteLine("Successfully created the file.")
            End If
        Catch ex As Exception
            DisplayException(ex)
        Finally
            dirPath = Nothing
            fInfo = Nothing
        End Try
    End Sub
    '
    ' Creates and saves an Xml file to sourcePath.
    '
    Private Sub WriteFileContent(ByVal totalElements As Integer)
        Dim doc As New XmlDocument()
        doc.PreserveWhitespace = True
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", Nothing, "yes"))
        doc.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
        Dim root As XmlElement = doc.CreateElement("FileInfo.MoveTo")
        Dim index As Integer = 0
        Dim elem As XmlElement
        While index < totalElements
            elem = doc.CreateElement("MyElement")
            elem.SetAttribute("Index", index.ToString())
            elem.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
            elem.AppendChild(doc.CreateTextNode(String.Format _
             ("MyElement at position {0}.", index)))
            elem.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
            root.AppendChild(elem)
            index += 1
        End While
        doc.AppendChild(root)
        doc.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
        doc.Save(sourcePath)
    End Sub
    '
    ' Displays FullName, CreationTime, and LastWriteTime of the supplied
    ' FileInfo instance, then displays the text of the file.
    '
    Private Sub DisplayFileProperties(ByVal fInfo As FileInfo)
        Console.WriteLine("The FileInfo instance shows these property values.")
        Dim reader As StreamReader = Nothing
        Try
            Console.Write("FullName: ")
            Console.WriteLine(fInfo.FullName)
            Console.Write("CreationTime: ")
            Console.WriteLine(fInfo.CreationTime)
            Console.Write("LastWriteTime: ")
            Console.WriteLine(fInfo.LastWriteTime)
            Console.WriteLine()
            Console.WriteLine("File contents:")
            Console.WriteLine()
            reader = New StreamReader(fInfo.FullName)
            While Not reader.EndOfStream
                Console.WriteLine(reader.ReadLine())
            End While
            Console.WriteLine()
        Catch ex As Exception
            DisplayException(ex)
        Finally
            If Not reader Is Nothing Then
                reader.Close()
                reader = Nothing
            End If
        End Try
    End Sub
    '
    ' Deletes the test directory and all its files and subdirectories.
    '
    Private Sub DeleteFiles()
        Try
            Dim dInfo As DirectoryInfo = New DirectoryInfo(Environment.GetFolderPath _
              (Environment.SpecialFolder.MyDocuments) + "\FileInfoTestDirectory")
            If dInfo.Exists Then
                dInfo.Delete(True)
                Console.WriteLine("Successfully deleted directories and files.")
            End If
            dInfo = Nothing
        Catch ex As Exception
            DisplayException(ex)
        End Try
    End Sub
    '
    ' Displays information about the supplied Exception. This
    ' code is not suitable for production applications.
    '
    Private Sub DisplayException(ByVal ex As Exception)
        Dim sb As New StringBuilder("An exception of type """)
        sb.Append(ex.GetType().FullName)
        sb.Append(""" has occurred.")
        sb.Append(ControlChars.CrLf)
        sb.Append(ex.Message)
        sb.Append(ControlChars.CrLf)
        sb.Append("Stack trace information:")
        sb.Append(ControlChars.CrLf)
        Dim matchCol As MatchCollection = Regex.Matches(ex.StackTrace, _
        "(at\s)(.+)(\.)([^\.]*)(\()([^\)]*)(\))((\sin\s)(.+)(:line )([\d]*))?")
        Dim L As Integer = matchCol.Count
        Dim y, K As Integer
        Dim argList() As String
        Dim matchObj As Match
        Dim x As Integer = 0
        While x < L
            matchObj = matchCol(x)
            sb.Append(ControlChars.CrLf)
            sb.Append(ControlChars.CrLf)
            sb.Append(matchObj.Result("$1 $2$3$4$5"))
            argList = matchObj.Groups(6).Value.Split(New Char() {","})
            K = argList.Length
            y = 0
            While y < K
                sb.Append(ControlChars.CrLf)
                sb.Append("    ")
                sb.Append(argList(y).Trim().Replace(" ", "        "))
                sb.Append(",")
                y += 1
            End While
            sb.Remove(sb.Length - 1, 1)
            sb.Append(ControlChars.CrLf)
            If 0 < matchObj.Groups(8).Length Then
                sb.Append(ControlChars.CrLf)
                sb.Append(matchObj.Result("$10"))
                sb.Append(ControlChars.CrLf)
                sb.Append(matchObj.Result("line $12"))
            End If
            x += 1
        End While
        argList = Nothing
        matchObj = Nothing
        matchCol = Nothing
        Console.WriteLine(sb.ToString())
        sb = Nothing
        Return
    End Sub
End Module

' Welcome.
' This application demonstrates the FileInfo.MoveTo method.
' Press any key to start.
' 
'     Checking whether C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml exists.
' Creating file C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml.
' Adding data to the file.
' Successfully created the file.
' The FileInfo instance shows these property values.
' FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml
' CreationTime: 4/18/2006 1:38:19 PM
' LastWriteTime: 4/18/2006 1:38:19 PM
' 
' File contents:
' 
' <?xml version="1.0" standalone="yes"?>
' <FileInfo.MoveTo><MyElement Index="0">
' MyElement at position 0.
' </MyElement><MyElement Index="1">
' MyElement at position 1.
' </MyElement><MyElement Index="2">
' MyElement at position 2.
' </MyElement><MyElement Index="3">
' MyElement at position 3.
' </MyElement><MyElement Index="4">
' MyElement at position 4.
' </MyElement><MyElement Index="5">
' MyElement at position 5.
' </MyElement><MyElement Index="6">
' MyElement at position 6.
' </MyElement><MyElement Index="7">
' MyElement at position 7.
' </MyElement><MyElement Index="8">
' MyElement at position 8.
' </MyElement><MyElement Index="9">
' MyElement at position 9.
' </MyElement></FileInfo.MoveTo>
' 
' Preparing to move the file to
' C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\DestFile.xml.
' File moved to
' C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\DestFile.xml
' The FileInfo instance shows these property values.
' FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\DestFile.xml
' CreationTime: 4/18/2006 1:38:19 PM
' LastWriteTime: 4/18/2006 1:38:19 PM
' 
' File contents:
' 
' <?xml version="1.0" standalone="yes"?>
' <FileInfo.MoveTo><MyElement Index="0">
' MyElement at position 0.
' </MyElement><MyElement Index="1">
' MyElement at position 1.
' </MyElement><MyElement Index="2">
' MyElement at position 2.
' </MyElement><MyElement Index="3">
' MyElement at position 3.
' </MyElement><MyElement Index="4">
' MyElement at position 4.
' </MyElement><MyElement Index="5">
' MyElement at position 5.
' </MyElement><MyElement Index="6">
' MyElement at position 6.
' </MyElement><MyElement Index="7">
' MyElement at position 7.
' </MyElement><MyElement Index="8">
' MyElement at position 8.
' </MyElement><MyElement Index="9">
' MyElement at position 9.
' </MyElement></FileInfo.MoveTo>
' 
' Preparing to delete directories.
' Successfully deleted directories and files.
' Press the ENTER key to close this application.

설명

이 메서드는 디스크 볼륨에서 작동합니다. 예를 들어 파일 c:\MyFile.txt d:\public로 이동하고 NewFile.txt 이름을 바꿀 수 있습니다.

이 메서드는 대상 파일이 이미 있는 경우 덮어쓰지 않습니다. 이를 위해 대신 호출 MoveTo(String, Boolean) 합니다.

추가 정보

적용 대상

MoveTo(String, Boolean)

새 파일 이름을 지정하고 대상 파일이 이미 있으면 덮어쓰는 옵션을 제공하여, 지정된 파일을 새 위치로 이동합니다.

public:
 void MoveTo(System::String ^ destFileName, bool overwrite);
public void MoveTo (string destFileName, bool overwrite);
member this.MoveTo : string * bool -> unit
Public Sub MoveTo (destFileName As String, overwrite As Boolean)

매개 변수

destFileName
String

파일을 이동할 경로입니다. 이 경로에서 다른 파일 이름을 지정할 수 있습니다.

overwrite
Boolean

대상 파일이 이미 있는 경우 덮어쓰려면 true로 설정하고, 그렇지 않으면 false로 설정합니다.

예외

대상 디바이스가 준비되지 않은 경우와 같은 I/O 오류가 발생했습니다.

destFileName이(가) null인 경우

2.1 이전의 .NET Framework 및 .NET Core 버전: destFileName 비어 있거나 공백만 포함하거나 잘못된 문자를 포함합니다.

호출자에게 필요한 권한이 없는 경우

destFileName 가 읽기 전용이거나 디렉터리입니다.

파일을 찾을 수 없습니다.

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

destFileName의 문자열 중간에 콜론(:)이 있습니다.

예제

다음 예제에서는 파일을 다른 위치로 이동하고 파일 이름을 바꾸는 방법을 보여 줍니다.


using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace Microsoft.Samples.MoveTo.CS
{

    class Program
    {
        private static string sourcePath = Environment.GetFolderPath
            (Environment.SpecialFolder.MyDocuments) +
            @"\FileInfoTestDirectory\MoveFrom\FromFile.xml";
        
        private static string destPath = Environment.GetFolderPath
            (Environment.SpecialFolder.MyDocuments) +
            @"\FileInfoTestDirectory\DestFile.xml";
        //
        // The main entry point for the application.
        //
        [STAThread()] static void Main ()
        {
            // Change Console properties to make it obvious that
            // the application is starting.
            Console.Clear();
            // Move it to the upper left corner of the screen.
            Console.SetWindowPosition(0, 0);
            // Make it very large.
            Console.SetWindowSize(Console.LargestWindowWidth - 24,
                Console.LargestWindowHeight - 16);
            Console.WriteLine("Welcome.");
            Console.WriteLine("This application demonstrates the FileInfo.MoveTo method.");
            Console.WriteLine("Press any key to start.");
            string s = Console.ReadLine();
            Console.Write("    Checking whether ");
            Console.Write(sourcePath);
            Console.WriteLine(" exists.");
            FileInfo fInfo = new FileInfo (sourcePath);
            EnsureSourceFileExists();
            DisplayFileProperties(fInfo);
            Console.WriteLine("Preparing to move the file to ");
            Console.Write(destPath);
            Console.WriteLine(".");
            MoveFile(fInfo);
            DisplayFileProperties(fInfo);
            Console.WriteLine("Preparing to delete directories.");
            DeleteFiles();
            Console.WriteLine("Press the ENTER key to close this application.");
            s = Console.ReadLine();
        }
        //
        // Moves the supplied FileInfo instance to destPath.
        //
        private static void MoveFile(FileInfo fInfo)
        {
            try
            {
                fInfo.MoveTo(destPath);
                Console.WriteLine("File moved to ");
                Console.WriteLine(destPath);
            } catch (Exception ex) {
                DisplayException(ex);
            }
        }
        //
        // Ensures that the test directories
        // and the file FromFile.xml all exist.
        //
        private static void EnsureSourceFileExists()
        {
            FileInfo fInfo = new FileInfo(sourcePath);
            string dirPath = fInfo.Directory.FullName;
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            if (File.Exists(destPath))
            {
                File.Delete(destPath);
            }
            Console.Write("Creating file ");
            Console.Write(fInfo.FullName);
            Console.WriteLine(".");
            try
            {
                if (!fInfo.Exists)
                {
                    Console.WriteLine("Adding data to the file.");
                    WriteFileContent(10);
                    Console.WriteLine("Successfully created the file.");
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
            finally
            {
                dirPath = null;
            }
        }
        //
        // Creates and saves an Xml file to sourcePath.
        //
        private static void WriteFileContent(int totalElements)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, "yes"));
            doc.AppendChild(doc.CreateWhitespace("\r\n"));
            XmlElement root = doc.CreateElement("FileInfo.MoveTo");
            root.AppendChild(doc.CreateWhitespace("\r\n"));
            int index = 0;
            XmlElement elem;
            while (index < totalElements)
            {
                
                elem = doc.CreateElement("MyElement");
                elem.SetAttribute("Index", index.ToString());
                elem.AppendChild(doc.CreateWhitespace("\r\n"));
                elem.AppendChild(doc.CreateTextNode(String.Format
                    ("MyElement at position {0}.", index)));
                elem.AppendChild(doc.CreateWhitespace("\r\n"));
                root.AppendChild(elem);
                root.AppendChild(doc.CreateWhitespace("\r\n"));
                index++;
            }
            doc.AppendChild(root);
            doc.AppendChild(doc.CreateWhitespace("\r\n"));
            doc.Save(sourcePath);
            elem = null;
            root = null;
            doc = null;
        }
        //
        // Displays FullName, CreationTime, and LastWriteTime of the supplied
        // FileInfo instance, then displays the text of the file.
        //
        private static void DisplayFileProperties(FileInfo fInfo)
        {
            Console.WriteLine("The FileInfo instance shows these property values.");
            StreamReader reader = null;
            try
            {
                Console.Write("FullName: ");
                Console.WriteLine(fInfo.FullName);
                Console.Write("CreationTime: ");
                Console.WriteLine(fInfo.CreationTime);
                Console.Write("LastWriteTime: ");
                Console.WriteLine(fInfo.LastWriteTime);
                Console.WriteLine();
                Console.WriteLine("File contents:");
                Console.WriteLine();
                reader = new StreamReader(fInfo.FullName);
                while (!reader.EndOfStream)
                {
                    Console.WriteLine(reader.ReadLine());
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                reader = null;
            }
        }
        //
        // Deletes the test directory and all its files and subdirectories.
        //
        private static void DeleteFiles()
        {
            try
            {
                DirectoryInfo dInfo = new DirectoryInfo(Environment.GetFolderPath
                    (Environment.SpecialFolder.MyDocuments) + "\\FileInfoTestDirectory");
                if (dInfo.Exists)
                {
                    dInfo.Delete(true);
                    Console.WriteLine("Successfully deleted directories and files.");
                }
                dInfo = null;
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
        //
        // Displays information about the supplied Exception. This
        // code is not suitable for production applications.
        //
        private static void DisplayException(Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("An exception of type \"");
            sb.Append(ex.GetType().FullName);
            sb.Append("\" has occurred.\r\n");
            sb.Append(ex.Message);
            sb.Append("\r\nStack trace information:\r\n");
            MatchCollection matchCol = Regex.Matches(ex.StackTrace,
@"(at\s)(.+)(\.)([^\.]*)(\()([^\)]*)(\))((\sin\s)(.+)(:line )([\d]*))?");
            int L = matchCol.Count;
            string[] argList;
            Match matchObj;
            int y, K;
            for(int x = 0; x < L; x++)
            {
                matchObj = matchCol[x];
                sb.Append(matchObj.Result("\r\n\r\n$1 $2$3$4$5"));
                argList = matchObj.Groups[6].Value.Split(new char[] { ',' });
                K = argList.Length;
                for (y = 0; y < K; y++)
                {
                    sb.Append("\r\n    ");
                    sb.Append(argList[y].Trim().Replace(" ", "        "));
                    sb.Append(',');
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("\r\n)");
                if (0 < matchObj.Groups[8].Length)
                {
                    sb.Append(matchObj.Result("\r\n$10\r\nline $12"));
                }
            }
            argList = null;
            matchObj = null;
            matchCol = null;
            Console.WriteLine(sb.ToString());
            sb = null;
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
// Welcome.
// This application demonstrates the FileInfo.MoveTo method.
// Press any key to start.
//
//     Checking whether C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml exists.
// Creating file C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml.
// Adding data to the file.
// Successfully created the file.
// The FileInfo instance shows these property values.
// FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.

// Preparing to move the file to
// C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml.
// File moved to
// C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml
// The FileInfo instance shows these property values.
// FullName: C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
//
// Preparing to delete directories.
// Successfully deleted directories and files.
// Press the ENTER key to close this application.
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Xml

Module Program

    Private sourcePath As String = Environment.GetFolderPath _
    (Environment.SpecialFolder.MyDocuments) & _
    "\FileInfoTestDirectory\MoveFrom\FromFile.xml"
    '
    Private destPath As String = Environment.GetFolderPath _
    (Environment.SpecialFolder.MyDocuments) & _
    "\FileInfoTestDirectory\DestFile.xml"
    '
    ' The main entry point for the application.
    '
    <STAThread()> Sub Main()
        ' Change Console properties to make it obvious that 
        ' the application is starting.
        Console.Clear()
        ' Move it to the upper left corner of the screen.
        Console.SetWindowPosition(0, 0)
        ' Make it very large.
        Console.SetWindowSize(Console.LargestWindowWidth - 24, _
            Console.LargestWindowHeight - 16)
        Console.WriteLine("Welcome.")
        Console.WriteLine("This application demonstrates the FileInfo.MoveTo method.")
        Console.WriteLine("Press any key to start.")
        Dim s As String = Console.ReadLine()
        Console.Write("    Checking whether ")
        Console.Write(sourcePath)
        Console.WriteLine(" exists.")
        Dim fInfo As FileInfo = New FileInfo(sourcePath)
        EnsureSourceFileExists()
        DisplayFileProperties(fInfo)
        Console.WriteLine("Preparing to move the file to ")
        Console.Write(destPath)
        Console.WriteLine(".")
        MoveFile(fInfo)
        DisplayFileProperties(fInfo)
        Console.WriteLine("Preparing to delete directories.")
        DeleteFiles()
        Console.WriteLine("Press the ENTER key to close this application.")
        s = Console.ReadLine()
    End Sub
    '
    ' Moves the supplied FileInfo instance to destPath.
    '
    Private Sub MoveFile(ByVal fInfo As FileInfo)
        Try
            fInfo.MoveTo(destPath)
            Console.WriteLine("File moved to ")
            Console.WriteLine(destPath)
        Catch ex As Exception
            DisplayException(ex)
        End Try
    End Sub
    '
    ' Ensures that the test directories 
    ' and the file FromFile.xml all exist.
    '
    Private Sub EnsureSourceFileExists()
        ' Create a FileInfo instance, and get the full path 
        ' to the parent directory.
        Dim fInfo As FileInfo = New FileInfo(sourcePath)
        Dim dirPath As String = fInfo.Directory.FullName
        ' If the directory does not exist, create it.
        If Not Directory.Exists(dirPath) Then
            Directory.CreateDirectory(dirPath)
        End If
        ' If DestFile.xml exists, delete it.
        If File.Exists(destPath) Then
            File.Delete(destPath)
        End If
        Console.Write("Creating file ")
        Console.Write(fInfo.FullName)
        Console.WriteLine(".")
        Try
            If Not fInfo.Exists Then
                ' Call WriteFileContent to create the file.
                Console.WriteLine("Adding data to the file.")
                WriteFileContent(10)
                Console.WriteLine("Successfully created the file.")
            End If
        Catch ex As Exception
            DisplayException(ex)
        Finally
            dirPath = Nothing
            fInfo = Nothing
        End Try
    End Sub
    '
    ' Creates and saves an Xml file to sourcePath.
    '
    Private Sub WriteFileContent(ByVal totalElements As Integer)
        Dim doc As New XmlDocument()
        doc.PreserveWhitespace = True
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", Nothing, "yes"))
        doc.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
        Dim root As XmlElement = doc.CreateElement("FileInfo.MoveTo")
        Dim index As Integer = 0
        Dim elem As XmlElement
        While index < totalElements
            elem = doc.CreateElement("MyElement")
            elem.SetAttribute("Index", index.ToString())
            elem.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
            elem.AppendChild(doc.CreateTextNode(String.Format _
             ("MyElement at position {0}.", index)))
            elem.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
            root.AppendChild(elem)
            index += 1
        End While
        doc.AppendChild(root)
        doc.AppendChild(doc.CreateWhitespace(ControlChars.CrLf))
        doc.Save(sourcePath)
    End Sub
    '
    ' Displays FullName, CreationTime, and LastWriteTime of the supplied
    ' FileInfo instance, then displays the text of the file.
    '
    Private Sub DisplayFileProperties(ByVal fInfo As FileInfo)
        Console.WriteLine("The FileInfo instance shows these property values.")
        Dim reader As StreamReader = Nothing
        Try
            Console.Write("FullName: ")
            Console.WriteLine(fInfo.FullName)
            Console.Write("CreationTime: ")
            Console.WriteLine(fInfo.CreationTime)
            Console.Write("LastWriteTime: ")
            Console.WriteLine(fInfo.LastWriteTime)
            Console.WriteLine()
            Console.WriteLine("File contents:")
            Console.WriteLine()
            reader = New StreamReader(fInfo.FullName)
            While Not reader.EndOfStream
                Console.WriteLine(reader.ReadLine())
            End While
            Console.WriteLine()
        Catch ex As Exception
            DisplayException(ex)
        Finally
            If Not reader Is Nothing Then
                reader.Close()
                reader = Nothing
            End If
        End Try
    End Sub
    '
    ' Deletes the test directory and all its files and subdirectories.
    '
    Private Sub DeleteFiles()
        Try
            Dim dInfo As DirectoryInfo = New DirectoryInfo(Environment.GetFolderPath _
              (Environment.SpecialFolder.MyDocuments) + "\FileInfoTestDirectory")
            If dInfo.Exists Then
                dInfo.Delete(True)
                Console.WriteLine("Successfully deleted directories and files.")
            End If
            dInfo = Nothing
        Catch ex As Exception
            DisplayException(ex)
        End Try
    End Sub
    '
    ' Displays information about the supplied Exception. This
    ' code is not suitable for production applications.
    '
    Private Sub DisplayException(ByVal ex As Exception)
        Dim sb As New StringBuilder("An exception of type """)
        sb.Append(ex.GetType().FullName)
        sb.Append(""" has occurred.")
        sb.Append(ControlChars.CrLf)
        sb.Append(ex.Message)
        sb.Append(ControlChars.CrLf)
        sb.Append("Stack trace information:")
        sb.Append(ControlChars.CrLf)
        Dim matchCol As MatchCollection = Regex.Matches(ex.StackTrace, _
        "(at\s)(.+)(\.)([^\.]*)(\()([^\)]*)(\))((\sin\s)(.+)(:line )([\d]*))?")
        Dim L As Integer = matchCol.Count
        Dim y, K As Integer
        Dim argList() As String
        Dim matchObj As Match
        Dim x As Integer = 0
        While x < L
            matchObj = matchCol(x)
            sb.Append(ControlChars.CrLf)
            sb.Append(ControlChars.CrLf)
            sb.Append(matchObj.Result("$1 $2$3$4$5"))
            argList = matchObj.Groups(6).Value.Split(New Char() {","})
            K = argList.Length
            y = 0
            While y < K
                sb.Append(ControlChars.CrLf)
                sb.Append("    ")
                sb.Append(argList(y).Trim().Replace(" ", "        "))
                sb.Append(",")
                y += 1
            End While
            sb.Remove(sb.Length - 1, 1)
            sb.Append(ControlChars.CrLf)
            If 0 < matchObj.Groups(8).Length Then
                sb.Append(ControlChars.CrLf)
                sb.Append(matchObj.Result("$10"))
                sb.Append(ControlChars.CrLf)
                sb.Append(matchObj.Result("line $12"))
            End If
            x += 1
        End While
        argList = Nothing
        matchObj = Nothing
        matchCol = Nothing
        Console.WriteLine(sb.ToString())
        sb = Nothing
        Return
    End Sub
End Module

' Welcome.
' This application demonstrates the FileInfo.MoveTo method.
' Press any key to start.
' 
'     Checking whether C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml exists.
' Creating file C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml.
' Adding data to the file.
' Successfully created the file.
' The FileInfo instance shows these property values.
' FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml
' CreationTime: 4/18/2006 1:38:19 PM
' LastWriteTime: 4/18/2006 1:38:19 PM
' 
' File contents:
' 
' <?xml version="1.0" standalone="yes"?>
' <FileInfo.MoveTo><MyElement Index="0">
' MyElement at position 0.
' </MyElement><MyElement Index="1">
' MyElement at position 1.
' </MyElement><MyElement Index="2">
' MyElement at position 2.
' </MyElement><MyElement Index="3">
' MyElement at position 3.
' </MyElement><MyElement Index="4">
' MyElement at position 4.
' </MyElement><MyElement Index="5">
' MyElement at position 5.
' </MyElement><MyElement Index="6">
' MyElement at position 6.
' </MyElement><MyElement Index="7">
' MyElement at position 7.
' </MyElement><MyElement Index="8">
' MyElement at position 8.
' </MyElement><MyElement Index="9">
' MyElement at position 9.
' </MyElement></FileInfo.MoveTo>
' 
' Preparing to move the file to
' C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\DestFile.xml.
' File moved to
' C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\DestFile.xml
' The FileInfo instance shows these property values.
' FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\DestFile.xml
' CreationTime: 4/18/2006 1:38:19 PM
' LastWriteTime: 4/18/2006 1:38:19 PM
' 
' File contents:
' 
' <?xml version="1.0" standalone="yes"?>
' <FileInfo.MoveTo><MyElement Index="0">
' MyElement at position 0.
' </MyElement><MyElement Index="1">
' MyElement at position 1.
' </MyElement><MyElement Index="2">
' MyElement at position 2.
' </MyElement><MyElement Index="3">
' MyElement at position 3.
' </MyElement><MyElement Index="4">
' MyElement at position 4.
' </MyElement><MyElement Index="5">
' MyElement at position 5.
' </MyElement><MyElement Index="6">
' MyElement at position 6.
' </MyElement><MyElement Index="7">
' MyElement at position 7.
' </MyElement><MyElement Index="8">
' MyElement at position 8.
' </MyElement><MyElement Index="9">
' MyElement at position 9.
' </MyElement></FileInfo.MoveTo>
' 
' Preparing to delete directories.
' Successfully deleted directories and files.
' Press the ENTER key to close this application.

설명

이 메서드는 디스크 볼륨에서 작동합니다. 예를 들어 파일 c:\MyFile.txt d:\public로 이동하고 NewFile.txt 이름을 바꿀 수 있습니다.

추가 정보

적용 대상