Question

Comment lire un tableau d'octets brut de tout fichier, et écrire que tableau d'octets de retour dans un nouveau fichier?

Était-ce utile?

La solution

(edit: notez que la question a changé, il n'a pas mentionné byte[] au départ, voir révision 1 )

Eh bien, File.Copy saute à l'esprit; mais sinon cela ressemble à un scénario de 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);
        }
    }

Autres conseils

byte[] data = File.ReadAllBytes(path1);
File.WriteAllBytes(path2, data);

Savez-vous sur le TextReader et < a href = "http://msdn.microsoft.com/en-us/library/system.io.textwriter.aspx" rel = "nofollow noreferrer"> TextWriter , et leurs descendants StreamReader et StreamWriter ? Je pense que ceux-ci vont résoudre votre problème parce qu'ils gèrent les codages, BinaryReader ne sait pas encodages ou même texte, il ne concerne que les octets.

Comment lire le texte à partir d'un fichier

Comment écrire un texte à un fichier

Ceci est une excellente introduction à fichier IO et codages.

Ajout d'une réponse à la date,

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        source.CopyTo(dest);
    }
}

vous pouvez spécifier la taille du tampon

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        source.CopyTo(dest, 2048); // or something bigger.
    }
}

ou vous pouvez effectuer l'opération sur un autre thread,

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        await source.CopyToAsync(dest);
    }
}

qui serait utile lorsque le thread principal doit effectuer d'autres tâches, comme avec WPF et Windows App Store.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top