Asked  7 Months ago    Answers:  5   Viewed   49 times

I want to copy the entire contents of a directory from one location to another in C#.

There doesn't appear to be a way to do this using System.IO classes without lots of recursion.

There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic:

new Microsoft.VisualBasic.Devices.Computer().
    FileSystem.CopyDirectory( sourceFolder, outputFolder );

This seems like a rather ugly hack. Is there a better way?

 Answers

63

Much easier

private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
    {
        Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
    }

    //Copy all the files & Replaces any files with the same name
    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
    {
        File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
    }
}
Tuesday, June 1, 2021
 
Oshrib
answered 7 Months ago
40

As @stefan said using fopen() with "w" mode will do the job for you. When you open a file with "w" flag it creates an empty file for writing. If a file with the same name already exists its contents are erased and the file is treated as an empty new file.

If the file is already open you can use freopen() function from stdio.h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.

Wednesday, July 28, 2021
 
Corne
answered 5 Months ago
29

Rather than deal with all that Marshalling, it's pretty trivial to just "roll your own" copier that goes chunk by chunk:

private static void CopyFile(string source, string destination, int bytesPerChunk)
{
    int bytesRead = 0;

    using (FileStream fs = new FileStream(source, FileMode.Open, FileAccess.Read))
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            using (FileStream fsDest = new FileStream(destination, FileMode.Create))
            {
                BinaryWriter bw = new BinaryWriter(fsDest);
                byte[] buffer;

                for (int i = 0; i < fs.Length; i += bytesPerChunk)
                {
                    buffer = br.ReadBytes(bytesPerChunk);
                    bw.Write(buffer);
                    bytesRead += bytesPerChunk;
                    ReportProgress(bytesRead, fs.Length);  //report the progress
                }
            }
        }
    }
}
Saturday, August 7, 2021
 
Awais Qarni
answered 4 Months ago
23

A network stream remains open until it is closed by one end of the stream. CopyTo() copies all data from the stream, waiting until the stream ends. If the server is not sending data, the stream does not end or close and CopyTo() dutifully waits for more data or for the stream to end. The server on the other end of the stream must close the stream for it to end and CopyTo() to return.

Google "TcpClient Tutorial" or "TcpCLient Sample" to get some good pages showing other ways you might use them, such as checking NetworkStream.DataAvailable to see if there is data waiting or if the stream is still open with no data. To just read some data and not wait for the stream to close you would use NetworkStream.Read() or wrap it in a StreamReader and use ReadLine(). It all depends on the server you are connecting to and what you are trying to accomplish.

Thursday, August 26, 2021
 
LunaLoveDove
answered 4 Months ago
89

Something like this, may be?

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream. Note "b" to avoid DOS/UNIX new line conversion.
stream = fopen(argv[1], "rb");

//Seek to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (add 1 for the , since fread won't add it)
contents = malloc(fileSize+1);

//Read the file 
size_t size=fread(contents,1,fileSize,stream);
contents[size]=0; // Add terminating zero.

//Print it again for debugging
printf("Read %sn", contents);

//Close the file
fclose(stream);
free(contents);
Tuesday, August 31, 2021
 
stand
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share