FileInfo.CopyTo Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Copia un file esistente in un nuovo file.
Overload
CopyTo(String) |
Copia un file esistente in un nuovo file, non consentendo la sovrascrittura di un file esistente. |
CopyTo(String, Boolean) |
Copia un file esistente in un nuovo file, consentendo la sovrascrittura di un file esistente. |
CopyTo(String)
- Origine:
- FileInfo.cs
- Origine:
- FileInfo.cs
- Origine:
- FileInfo.cs
Copia un file esistente in un nuovo file, non consentendo la sovrascrittura di un file esistente.
public:
System::IO::FileInfo ^ CopyTo(System::String ^ destFileName);
public System.IO.FileInfo CopyTo (string destFileName);
member this.CopyTo : string -> System.IO.FileInfo
Public Function CopyTo (destFileName As String) As FileInfo
Parametri
- destFileName
- String
Nome del nuovo file in cui copiare.
Restituisce
Nuovo file con percorso completo.
Eccezioni
.NET Framework e versioni di .NET Core precedenti alla versione 2.1: destFileName
è vuota, contiene solo spazi vuoti o contiene caratteri non validi.
Si è verificato un errore o il file di destinazione esiste già.
Il chiamante non dispone dell'autorizzazione richiesta.
destFileName
è null
.
È stato passato un percorso di directory o il file è stato spostato in una diversa unità.
La directory specificata in destFileName
non esiste.
Il percorso specificato, il nome file o entrambi superano la lunghezza massima definita dal sistema.
destFileName
contiene due punti (:) all'interno della stringa ma non specifica il volume.
Esempio
Nell'esempio seguente vengono illustrati entrambi gli overload del CopyTo
metodo.
using namespace System;
using namespace System::IO;
int main()
{
String^ path = "c:\\MyTest.txt";
String^ path2 = "c:\\MyTest.txttemp";
FileInfo^ fi1 = gcnew FileInfo( path );
FileInfo^ fi2 = gcnew FileInfo( path2 );
try
{
// Create the file and clean up handles.
FileStream^ fs = fi1->Create();
if ( fs )
delete (IDisposable^)fs;
//Ensure that the target does not exist.
fi2->Delete();
//Copy the file.
fi1->CopyTo( path2 );
Console::WriteLine( "{0} was copied to {1}.", path, path2 );
//Try to copy it again, which should succeed.
fi1->CopyTo( path2, true );
Console::WriteLine( "The second Copy operation succeeded, which is expected." );
}
catch ( Exception^ )
{
Console::WriteLine( "Double copying was not allowed, which is not expected." );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The second Copy operation succeeded, which is expected.
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\SoureFile.txt";
string path2 = @"c:\NewFile.txt";
FileInfo fi1 = new FileInfo(path);
FileInfo fi2 = new FileInfo(path2);
try
{
// Create the source file.
using (FileStream fs = fi1.Create()) { }
//Ensure that the target file does not exist.
if (File.Exists(path2))
{
fi2.Delete();
}
//Copy the file.f
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
}
Imports System.IO
Public Class Test
Public Shared Sub Main()
'Specify the directories you want to manipulate.
Dim path As String = "c:\SourceFile.txt"
Dim path2 As String = "c:\NewFile.txt"
Dim fi As FileInfo = New FileInfo(path)
Dim fi2 As FileInfo = New FileInfo(path2)
Try
Using fs As FileStream = fi.Create()
End Using
'Ensure that the target does not exist.
If File.Exists(path2) Then
fi2.Delete()
End If
'Copy the file.
fi.CopyTo(path2)
Console.WriteLine("{0} was copied to {1}.", path, path2)
Catch ioex As IOException
Console.WriteLine(ioex.Message)
End Try
End Sub
End Class
Nell'esempio seguente viene illustrata la copia di un file in un altro file, generando un'eccezione se il file di destinazione esiste già.
using namespace System;
using namespace System::IO;
int main()
{
try
{
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
FileInfo^ fi = gcnew FileInfo( "temp.txt" );
// Create a writer, ready to add entries to the file.
StreamWriter^ sw = fi->AppendText();
sw->WriteLine( "Add as many lines as you like..." );
sw->WriteLine( "Add another line to the output..." );
sw->Flush();
sw->Close();
// Get the information out of the file and display it.
StreamReader^ sr = gcnew StreamReader( fi->OpenRead() );
Console::WriteLine( "This is the information in the first file:" );
while ( sr->Peek() != -1 )
Console::WriteLine( sr->ReadLine() );
// Copy this file to another file. The file will not be overwritten if it already exists.
FileInfo^ newfi = fi->CopyTo( "newTemp.txt" );
// Get the information out of the new file and display it.* sr = new StreamReader(newfi->OpenRead());
Console::WriteLine( "{0}This is the information in the second file:", Environment::NewLine );
while ( sr->Peek() != -1 )
Console::WriteLine( sr->ReadLine() );
}
catch ( Exception^ e )
{
Console::WriteLine( e->Message );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//
//This is the information in the second file:
using System;
using System.IO;
public class CopyToTest
{
public static void Main()
{
try
{
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
FileInfo fi = new FileInfo("temp.txt");
// Create a writer, ready to add entries to the file.
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// Get the information out of the file and display it.
StreamReader sr = new StreamReader(fi.OpenRead());
Console.WriteLine("This is the information in the first file:");
while (sr.Peek() != -1)
Console.WriteLine(sr.ReadLine());
// Copy this file to another file. The file will not be overwritten if it already exists.
FileInfo newfi = fi.CopyTo("newTemp.txt");
// Get the information out of the new file and display it.
sr = new StreamReader(newfi.OpenRead());
Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
while (sr.Peek() != -1)
Console.WriteLine(sr.ReadLine());
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
Imports System.IO
Public Class CopyToTest
Public Shared Sub Main()
Try
' Create a reference to a file, which might or might not exist.
' If it does not exist, it is not yet created.
Dim fi As New FileInfo("temp.txt")
' Create a writer, ready to add entries to the file.
Dim sw As StreamWriter = fi.AppendText()
sw.WriteLine("Add as many lines as you like...")
sw.WriteLine("Add another line to the output...")
sw.Flush()
sw.Close()
' Get the information out of the file and display it.
Dim sr As New StreamReader(fi.OpenRead())
Console.WriteLine("This is the information in the first file:")
While sr.Peek() <> -1
Console.WriteLine(sr.ReadLine())
End While
' Copy this file to another file.
Dim newfi As FileInfo = fi.CopyTo("newTemp.txt")
' Get the information out of the new file and display it.
sr = New StreamReader(newfi.OpenRead())
Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine)
While sr.Peek() <> -1
Console.WriteLine(sr.ReadLine())
End While
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
End Class
'This code produces output similar to the following;
'results may vary based on the computer/file structure/etc.:
'
'This is the information in the first file:
'Add as many lines as you like...
'Add another line to the output...
'
'This is the information in the second file:
'Add as many lines as you like...
'Add another line to the output...
Commenti
Utilizzare il CopyTo(String, Boolean) metodo per consentire la sovrascrittura di un file esistente.
Attenzione
Se possibile, evitare di usare nomi di file brevi (ad esempio XXXXXX~1.XXX) con questo metodo. Se due file hanno nomi di file brevi equivalenti, questo metodo potrebbe non riuscire e generare un'eccezione e/o generare un comportamento indesiderato
Vedi anche
- File e Stream I/O
- Procedura: Leggere testo da un file
- Procedura: Scrivere un testo in un file
- Procedura: Leggere e scrivere su un file di dati appena creato
Si applica a
CopyTo(String, Boolean)
- Origine:
- FileInfo.cs
- Origine:
- FileInfo.cs
- Origine:
- FileInfo.cs
Copia un file esistente in un nuovo file, consentendo la sovrascrittura di un file esistente.
public:
System::IO::FileInfo ^ CopyTo(System::String ^ destFileName, bool overwrite);
public System.IO.FileInfo CopyTo (string destFileName, bool overwrite);
member this.CopyTo : string * bool -> System.IO.FileInfo
Public Function CopyTo (destFileName As String, overwrite As Boolean) As FileInfo
Parametri
- destFileName
- String
Nome del nuovo file in cui copiare.
- overwrite
- Boolean
true
per consentire di sovrascrivere un file esistente; in caso contrario, false
.
Restituisce
Nuovo file oppure sovrascrittura di un file esistente se overwrite
è true
. Se il file esiste e overwrite
è false
, viene generata un'eccezione IOException.
Eccezioni
.NET Framework e versioni di .NET Core precedenti alla versione 2.1: destFileName
è vuota, contiene solo spazi vuoti o contiene caratteri non validi.
Si è verificato un errore o il file di destinazione esiste già e overwrite
è false
.
Il chiamante non dispone dell'autorizzazione richiesta.
destFileName
è null
.
La directory specificata in destFileName
non esiste.
È stato passato un percorso di directory o il file è stato spostato in una diversa unità.
Il percorso specificato, il nome file o entrambi superano la lunghezza massima definita dal sistema.
destFileName
contiene i due punti (:) all'interno della stringa.
Esempio
Nell'esempio seguente vengono illustrati entrambi gli overload del CopyTo
metodo.
using namespace System;
using namespace System::IO;
int main()
{
String^ path = "c:\\MyTest.txt";
String^ path2 = "c:\\MyTest.txttemp";
FileInfo^ fi1 = gcnew FileInfo( path );
FileInfo^ fi2 = gcnew FileInfo( path2 );
try
{
// Create the file and clean up handles.
FileStream^ fs = fi1->Create();
if ( fs )
delete (IDisposable^)fs;
//Ensure that the target does not exist.
fi2->Delete();
//Copy the file.
fi1->CopyTo( path2 );
Console::WriteLine( "{0} was copied to {1}.", path, path2 );
//Try to copy it again, which should succeed.
fi1->CopyTo( path2, true );
Console::WriteLine( "The second Copy operation succeeded, which is expected." );
}
catch ( Exception^ )
{
Console::WriteLine( "Double copying was not allowed, which is not expected." );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The second Copy operation succeeded, which is expected.
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\SoureFile.txt";
string path2 = @"c:\NewFile.txt";
FileInfo fi1 = new FileInfo(path);
FileInfo fi2 = new FileInfo(path2);
try
{
// Create the source file.
using (FileStream fs = fi1.Create()) { }
//Ensure that the target file does not exist.
if (File.Exists(path2))
{
fi2.Delete();
}
//Copy the file.f
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
}
Imports System.IO
Public Class Test
Public Shared Sub Main()
'Specify the directories you want to manipulate.
Dim path As String = "c:\SourceFile.txt"
Dim path2 As String = "c:\NewFile.txt"
Dim fi As FileInfo = New FileInfo(path)
Dim fi2 As FileInfo = New FileInfo(path2)
Try
Using fs As FileStream = fi.Create()
End Using
'Ensure that the target does not exist.
If File.Exists(path2) Then
fi2.Delete()
End If
'Copy the file.
fi.CopyTo(path2)
Console.WriteLine("{0} was copied to {1}.", path, path2)
Catch ioex As IOException
Console.WriteLine(ioex.Message)
End Try
End Sub
End Class
Nell'esempio seguente viene illustrata la copia di un file in un altro file, specificando se sovrascrivere un file già esistente.
using namespace System;
using namespace System::IO;
int main()
{
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
FileInfo^ fi = gcnew FileInfo( "temp.txt" );
// Create a writer, ready to add entries to the file.
StreamWriter^ sw = fi->AppendText();
sw->WriteLine( "Add as many lines as you like..." );
sw->WriteLine( "Add another line to the output..." );
sw->Flush();
sw->Close();
// Get the information out of the file and display it.
StreamReader^ sr = gcnew StreamReader( fi->OpenRead() );
Console::WriteLine( "This is the information in the first file:" );
while ( sr->Peek() != -1 )
Console::WriteLine( sr->ReadLine() );
// Copy this file to another file. The true parameter specifies
// that the file will be overwritten if it already exists.
FileInfo^ newfi = fi->CopyTo( "newTemp.txt", true );
// Get the information out of the new file and display it.* sr = new StreamReader( newfi->OpenRead() );
Console::WriteLine( "{0}This is the information in the second file:", Environment::NewLine );
while ( sr->Peek() != -1 )
Console::WriteLine( sr->ReadLine() );
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//This is the information in the second file:
//
using System;
using System.IO;
public class CopyToTest
{
public static void Main()
{
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
FileInfo fi = new FileInfo("temp.txt");
// Create a writer, ready to add entries to the file.
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// Get the information out of the file and display it.
StreamReader sr = new StreamReader( fi.OpenRead() );
Console.WriteLine("This is the information in the first file:");
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
// Copy this file to another file. The true parameter specifies
// that the file will be overwritten if it already exists.
FileInfo newfi = fi.CopyTo("newTemp.txt", true);
// Get the information out of the new file and display it.
sr = new StreamReader( newfi.OpenRead() );
Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...
//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...
Imports System.IO
Public Class CopyToTest
Public Shared Sub Main()
' Create a reference to a file, which might or might not exist.
' If it does not exist, it is not yet created.
Dim fi As New FileInfo("temp.txt")
' Create a writer, ready to add entries to the file.
Dim sw As StreamWriter = fi.AppendText()
sw.WriteLine("Add as many lines as you like...")
sw.WriteLine("Add another line to the output...")
sw.Flush()
sw.Close()
' Get the information out of the file and display it.
Dim sr As New StreamReader(fi.OpenRead())
Console.WriteLine("This is the information in the first file:")
While sr.Peek() <> -1
Console.WriteLine(sr.ReadLine())
End While
' Copy this file to another file. The true parameter specifies
' that the file will be overwritten if it already exists.
Dim newfi As FileInfo = fi.CopyTo("newTemp.txt", True)
' Get the information out of the new file and display it.
sr = New StreamReader(newfi.OpenRead())
Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine)
While sr.Peek() <> -1
Console.WriteLine(sr.ReadLine())
End While
End Sub
End Class
'This code produces output similar to the following;
'results may vary based on the computer/file structure/etc.:
'
'This is the information in the first file:
'Add as many lines as you like...
'Add another line to the output...
'
'This is the information in the second file:
'Add as many lines as you like...
'Add another line to the output...
'
Commenti
Usare questo metodo per consentire o impedire la sovrascrittura di un file esistente. Utilizzare il CopyTo(String) metodo per impedire la sovrascrittura di un file esistente per impostazione predefinita.
Attenzione
Se possibile, evitare di usare nomi di file brevi (ad esempio XXXXXX~1.XXX) con questo metodo. Se due file hanno nomi di file brevi equivalenti, questo metodo potrebbe non riuscire e generare un'eccezione e/o generare un comportamento indesiderato
Vedi anche
- File e Stream I/O
- Procedura: Leggere testo da un file
- Procedura: Scrivere un testo in un file
- Procedura: Leggere e scrivere su un file di dati appena creato