다음을 통해 공유


File.Move 메서드

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

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public Shared Sub Move ( _
    sourceFileName As String, _
    destFileName As String _
)
‘사용 방법
Dim sourceFileName As String
Dim destFileName As String

File.Move(sourceFileName, destFileName)
public static void Move (
    string sourceFileName,
    string destFileName
)
public:
static void Move (
    String^ sourceFileName, 
    String^ destFileName
)
public static void Move (
    String sourceFileName, 
    String destFileName
)
public static function Move (
    sourceFileName : String, 
    destFileName : String
)

매개 변수

  • sourceFileName
    이동할 파일의 이름입니다.
  • destFileName
    파일에 대한 새 경로입니다.

예외

예외 형식 조건

IOException

대상 파일이 이미 있는 경우

ArgumentNullException

sourceFileName 또는 destFileName이 Null 참조(Visual Basic의 경우 Nothing)인 경우

ArgumentException

sourceFileName 또는 destFileName이 길이가 0인 문자열이거나, 공백만 포함하거나 또는 InvalidPathChars로 정의된 잘못된 문자를 포함하는 경우

UnauthorizedAccessException

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

FileNotFoundException

sourceFileName을 찾을 수 없는 경우

PathTooLongException

지정된 경로 또는 파일 이름이 시스템에 정의된 최대 길이를 초과하는 경우. 예를 들어, Windows 기반 플랫폼에서는 경로에 248자 미만의 문자를 사용해야 하며 파일 이름에는 260자 미만의 문자를 사용해야 합니다.

DirectoryNotFoundException

sourceFileName 또는 destFileName에 지정된 경로가 잘못된 경우(예: 매핑되지 않은 드라이브의 경로를 지정한 경우)

NotSupportedException

sourceFileName 또는 destFileName의 형식이 잘못된 경우

설명

이 메서드는 디스크 볼륨 간에서 작동하며, 원본 및 대상이 같은 경우에도 예외를 throw하지 않습니다. 동일한 이름의 파일을 해당 디렉터리로 이동하여 파일을 대체하려는 경우에는 IOException이 발생합니다. Move 메서드를 사용하여 기존 파일을 덮어쓸 수는 없습니다.

sourceFileName 및 destFileName 인수에 상대 경로나 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리에 상대적으로 해석됩니다. 현재 작업 디렉터리를 얻는 방법에 대해서는 GetCurrentDirectory를 참조하십시오.

이 메서드의 사용에 대한 예제는 예제 단원을 참조하십시오. 다음 표에서는 일반적인 예 또는 관련된 I/O 작업의 예를 보여 줍니다.

수행 작업

참조 항목

텍스트 파일에 씁니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에서 읽습니다.

방법: 파일의 텍스트 읽기

파일에 텍스트를 추가합니다.

방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText

파일을 복사합니다.

File.Copy

FileInfo.CopyTo

디렉터리 이름을 바꾸거나 이동합니다.

Directory.Move

DirectoryInfo.MoveTo

예제

다음 예제에서는 파일을 이동합니다.

Imports System
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim path2 As String = "c:\temp2\MyTest.txt"

        Try
            If File.Exists(path) = False Then
                ' This statement ensures that the file is created,
                ' but the handle is not kept.
                Dim fs As FileStream = File.Create(path)
                fs.Close()
            End If

            ' Ensure that the target does not exist.
            If File.Exists(path2) Then
                File.Delete(path2)
            End If

            ' Move the file.
            File.Move(path, path2)
            Console.WriteLine("{0} moved to {1}", path, path2)

            ' See if the original file exists now.
            If File.Exists(path) Then
                Console.WriteLine("The original file still exists, which is unexpected.")
            Else
                Console.WriteLine("The original file no longer exists, which is expected.")
            End If
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp2\MyTest.txt";
        try 
        {
            if (!File.Exists(path)) 
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2)) 
            File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path)) 
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            } 
            else 
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
            }           

        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   String^ path2 = "c:\\temp2\\MyTest.txt";
   try
   {
      if (  !File::Exists( path ) )
      {
         
         // This statement ensures that the file is created,
         // but the handle is not kept.
         FileStream^ fs = File::Create( path );
         if ( fs )
                  delete (IDisposable^)fs;
      }
      
      // Ensure that the target does not exist.
      if ( File::Exists( path2 ) )
            File::Delete( path2 );
      
      // Move the file.
      File::Move( path, path2 );
      Console::WriteLine( "{0} was moved to {1}.", path, path2 );
      
      // See if the original exists now.
      if ( File::Exists( path ) )
      {
         Console::WriteLine( "The original file still exists, which is unexpected." );
      }
      else
      {
         Console::WriteLine( "The original file no longer exists, which is expected." );
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        String path = "c:\\temp\\MyTest.txt";
        String path2 = "c:\\temp2\\MyTest.txt";

        try {
            if (!(File.Exists(path))) {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                FileStream fs = File.Create(path);

                try {
                }
                finally {
                    fs.Dispose();
                }                
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2)) {
                File.Delete(path2);
            }

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path)) {
                Console.WriteLine("The original file still exists, " 
                    + "which is unexpected.");
            }
            else {
                Console.WriteLine("The original file no longer exists, " 
                    + "which is expected.");
            }
        }
        catch (System.Exception e) {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    } //main
} //Test

.NET Framework 보안

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

File 클래스
File 멤버
System.IO 네임스페이스

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기