C # - Come faccio a leggere e scrivere un file binario?
-
11-09-2019 - |
Domanda
Come posso leggere un array di byte grezzo da qualsiasi file, e scrivono che array di byte di nuovo in un nuovo file?
Soluzione
(edit: notare che la domanda è cambiato, ma non ha menzionato byte[]
inizialmente, vedere revisione 1 )
Bene, File.Copy
balza alla mente; ma per il resto questo suona come uno scenario Stream
:
using (Stream source = File.OpenRead(inPath))
using (Stream dest = File.Create(outPath)) {
byte[] buffer = new byte[2048]; // pick size
int bytesRead;
while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
dest.Write(buffer, 0, bytesRead);
}
}
Altri suggerimenti
byte[] data = File.ReadAllBytes(path1);
File.WriteAllBytes(path2, data);
Sai di TextReader e < a href = "http://msdn.microsoft.com/en-us/library/system.io.textwriter.aspx" rel = "nofollow noreferrer"> TextWriter , e loro discendenti StreamReader e StreamWriter ? Credo che questi saranno risolvere il problema perché trattano codifiche, BinaryReader non sa di codifiche o anche testo, si occupa solo di byte.
L'aggiunta di un aggiornato risposta,
using (var source = File.OpenRead(inPath))
{
using (var dest = File.Create(outPath))
{
source.CopyTo(dest);
}
}
è possibile specificare la dimensione del buffer
using (var source = File.OpenRead(inPath))
{
using (var dest = File.Create(outPath))
{
source.CopyTo(dest, 2048); // or something bigger.
}
}
o si potrebbe eseguire l'operazione su un altro thread,
using (var source = File.OpenRead(inPath))
{
using (var dest = File.Create(outPath))
{
await source.CopyToAsync(dest);
}
}
che sarebbe utile quando il thread principale ha a che fare altri lavori, come con WPF e Windows Store applicazioni.