Showing posts with label File System. Show all posts
Showing posts with label File System. Show all posts

c# Reading file occurs The process cannot access the file 'Path' because it is being used by another process.

                using(var fs = new System.IO.FileStream(@"Path", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                using (var sr = new System.IO.StreamReader(fs))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }

If you just need whole text not lines, then use this code for better performance
                            using (var fs = new System.IO.FileStream(res.path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                            using (var sr = new System.IO.StreamReader(fs))
                            {
                                return sr.ReadToEnd();
                            }

C# how to copy all files in a folder

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace CopyDir
{
    class Program
    {
        static void Main(string[] args)
        {
            string FromDir = @"c:\source";
            string ToDir = @"c:\destination";
            if (!Directory.Exists(ToDir))
 
                Directory.CreateDirectory(ToDir);
 
            string[] Files;
            Files = Directory.GetFileSystemEntries(FromDir);
 
            for (int k = 0; k < Files.Length; k++)
            {
                string FromFile = Path.GetFileName(Files[k]);
 
                FileAttributes FileAttr = File.GetAttributes(Files[k]);
 
                if ((FileAttr & FileAttributes.Directory)== FileAttributes.Directory)
                    continue;
 
                Console.WriteLine(FromFile);
 
        string arrival = ToDir + "\\" + FromFile;
        File.Copy(Files[k], arrival, true);
                 
            }
            Console.ReadLine();
         }
    }
}