onlyforbopi
5/22/2017 - 8:44 AM

FILE_OPERATIONS

FILE_OPERATIONS

  1. checkifFileExists - checkiffileexists.cs
  2. checkifdirectoryExists - checkifdirexists.cs
  3. FileOrDirExists - FileorDir Exists
  4. DeleteFolder - Delete a given Folder
  5. CopyFolder - Copy a given Folder
  6. GetallFilesinDir - Get all Files from a directory
  7. GetallSubdirsinDir - Get all Subdirectories from a directory
  8. FindReplaceinFile - File / Replace all patterns in file
  9. CountNumberofLines - Counts number of lines of text file
class Fileprocess
    {
        public string File_Path;
        Dictionary<string, string> niarxosfile = new Dictionary<string, string>();



        // Default Constructor




        // Constructor (with pathname)
        public Fileprocess(string File_Path)
        {
            File_Path = this.File_Path;        
        }

        // Method File Size
        public string get_file_size()
        {
            FileInfo fi = new FileInfo(File_Path);
            var size = fi.Length;
            return (String.Format("{0}", size));
        }

        // Method Basename
        public string get_file_basename()
        {
            FileInfo fi = new FileInfo(File_Path);
            string basename = fi.Name;
            return (string.Format("{0}", basename));
        }

        // Method Dirname
        public string get_file_dirname()
        {
            FileInfo fi = new FileInfo(File_Path);
            string basename = fi.DirectoryName;
            return (string.Format("{0}", basename));
        }

        // Method Last update
        public string get_last_update()
        {
            FileInfo fi = new FileInfo(File_Path);
            string lutime = fi.LastAccessTime.ToString();
            return (string.Format("{0}", lutime));
        }

        // Method Last Access
        public string get_last_access()
        {
            FileInfo fi = new FileInfo(File_Path);
            string latime = fi.LastAccessTime.ToString();
            return (string.Format("{0}", latime));
        }

        // Method Permissions
        
        // Method Check existence
        public bool Check_File_Exists()
        {
            //FileInfo fi = new FileInfo(File_Path);
            
            if (File.Exists(File_Path))
            {
                return true;
            }
            else
            {
                return false;
            }


        }

        // Method File Size in Lines
        public string File_Size_Lines()
        {
            var lineCount = File.ReadLines(File_Path).Count();
            return (string.Format("{0}", lineCount));
        }


        // Method Load to Dictionary
        public void TextFileToDictionary()
        {

            // PREPEI NA EINAI GLOBAL
            //Dictionary<string, string> niarxosfile = new Dictionary<string, string>();
            using (var sr = new StreamReader(File_Path))
            {
                string line = null;

                // while keys exist
                while ((line = sr.ReadLine()) != null)
                {
                    // slice
                    string AP = line.Substring(0, 11);
                    string REST = line.Substring(11, line.Length); 


                    // add the first slice to key
                    // everything else to value - WILL NEED FUTHER SLICING

                    niarxosfile.Add(AP, REST);
                }
            }


        }


        // Method Copy/Backup
        public void File_Backup()
        {
            FileInfo fi = new FileInfo(File_Path);
            
        }



    }
int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   // Here, instead of Console we can output in textboxes, etc
   Console.WriteLine (line);
   counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();

//


// READ FILES LINE BY LINE - METHOD1
var filestream = new System.IO.FileStream(textFilePath,
                                          System.IO.FileMode.Open,
                                          System.IO.FileAccess.Read,
                                          System.IO.FileShare.ReadWrite);
var file = new System.IO.StreamReader(filestream, System.Text.Encoding.UTF8, true, 128);

while ((lineOfText = file.ReadLine()) != null)
{
    //Do something with the lineOfText
}

// READ FILES LINE BY LINE - METHOD2 - Using StreamReader.ReadLine
// This is basically your method. For some reason you set the buffer 
// size to the smallest possible value (128). Increasing this will in general 
// increase performance. The default size is 1,024 and other good choices are 512 (the sector size in Windows) 
//or 4,096 (the cluster size in NTFS). You will have to run a benchmark to determine an optimal buffer size. 
//A bigger buffer is - if not faster - at least not slower than a smaller buffer.
//The FileStream constructor allows you to specify FileOptions. For example, if you are reading a large file sequentially 
//from beginning to end, you may benefit from FileOptions.SequentialScan. Again, benchmarking is the best thing you can do.


const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead(fileName))
  using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize)) {
    String line;
    while ((line = streamReader.ReadLine()) != null)
      // Process line
  }
  

//Using File.ReadLines
//This is very much like your own solution except that it is implemented using a StreamReader with a fixed buffer size of 1,024. 
//On my computer this results in slightly better performance compared to your code with the buffer size of 128. However, you can 
//get the same performance increase by using a larger buffer size. This method is implemented using an iterator block and does 
//not consume memory for all lines.

var lines = File.ReadLines(fileName);
foreach (var line in lines)
  // Process line
Using File.ReadAllLines

//This is very much like the previous method except that this method grows a list of strings used to create the returned array of 
//lines so the memory requirements are higher. However, it returns String[] and not an IEnumerable<String> allowing you to randomly 
//access the lines.

var lines = File.ReadAllLines(fileName);
foreach (var line in lines)
  // Process line
Using String.Split

//This method is considerably slower, at least on big files (tested on a 511 KB file), probably due to how String.Split is implemented. 
//It also allocates an array for all the lines increasing the memory required compared to your solution.

using (var streamReader = File.OpenText(fileName)) {
  var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  foreach (var line in lines)
    // Process line
}


//If you're just wanting to read lines in a file without doing much, according to these benchmarks, 
//the fastest way to read a file is the age old method of:

using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
               //do minimal amount of work here
        }
}


//However, if you have to do a lot with each line, then this article concludes that the best way is 
//the following (and it's faster to pre-allocate a string[] if you know how many lines you're going to read) :

AllLines = new string[MAX]; //only allocate memory here

using (StreamReader sr = File.OpenText(fileName))
{
        int x = 0;
        while (!sr.EndOfStream)
        {
               AllLines[x] = sr.ReadLine();
               x += 1;
        }
} //Finished. Close the file

//Now parallel process each line in the file
Parallel.For(0, AllLines.Length, x =>
{
    DoYourStuff(AllLines[x]); //do your work here
});

internal static bool FileExists(string name)
{
   return (File.Exists(name));
}
private static void DirectoryCopy(string sourceDirname, string destDirname, bool copySubDirs)
{
  ///////
  // Input: SourceDirectory, DestinationDirectory, flag (T/F) if we want to copy subdirs
  // Output: Exact Duplicate of original directory (with or w/o subdirs)
  // Usage: DirectoryCopy(Paths2.master_folder, Paths2.prod_folder, true)
  // Notes: Flag is set to true if we want to copy subdirectories or not
  
  // Get the subdirectories for the specified directory
  DirectoryInfo dir = new DirectoryInfo(sourceDirName);
  
  if (!Dir.Exists)
  {
    throw new DirectoryNotFoundException(
      "Source directory does not exist or could not be found:" + sourceDirName);
  }
  
  DirectoryInfo[] dirs = dir.GetDirectories();
  
  // if the Destination directory doesnt exist, create it
  if (!Directory.Exists(destDirName))
  {
    Directory.CreateDirectory(destDirName);
  }
  
  // Get the files in the origin directory and copy them to new location
  FileInfo[] files = dir.GetFiles();
  forech (FileInfo file in files)
  {
    string temppath = Path.Combine(destDirName, file.Name);
    file.CopyTo(temppath, false);
  }
  
  // If we re copying subdirectories, copy them and their contents to new location
  if (copySubDirs)
  {
    foreach (DirectoryInfo subdir in dirs)
    {
      string temppath = Path.Combine(destDirName, subdir.Name);
      DirectoryCopy(subdir.Fullname, temppath, copySubDirs);
    }
  }
}

//COUNT NUMBER OF LINES OF FILE - METHOD 1
var lineCount = File.ReadLines(@"C:\file.txt").Count();

//COUNT NUMBER OF LINES OF FILE - METHOD 2
var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
For a more efficient method you could do:

var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}


//COUNT NUMBER OF LINES OF FILE - METHOD 3
int lines = File.ReadAllLines("myfile").Length;

//COUNT NUMBER OF LINES OF FILE - METHOD 4

int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)
{
  count++;
}
reader.Close();
private void deleteFolder(string folder)
{
  //////
  // Input: folder path
  // Output: None, unless there's an exception
  // Usage: deleteFolder("/path/to...")
  // Notes: If the folder is already deleted, display message.
  //
  
  try {
    Directory.Delete(folder,true);
  }
  catch(Exception e)
  {
    MessageBox.Show("Production Folder already deleted\n" + e.Message)
  }
string[] subfiles = Directory.GetFiles(path)    


// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor
{
    public static void Main(string[] args)
    {
        foreach(string path in args)
        {
            if(File.Exists(path))
            {
                // This path is a file
                ProcessFile(path);
            }
            else if(Directory.Exists(path))
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }
        }
    }

    // Process all files in the directory passed in, recurse on any directories
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path)
    {
        Console.WriteLine("Processed file '{0}'.", path);	
    }
}


// Get all files with directory, and pattern

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Only get files that begin with the letter "c".
            string[] dirs = Directory.GetFiles(@"c:\", "c*");
            Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
            foreach (string dir in dirs)
            {
                Console.WriteLine(dir);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

string[] subdirs = Directory.GetDirectories(path)
1. checkifFileExists       - checkiffileexists.cs
2. checkifdirectoryExists  - checkifdirexists.cs
3. FileOrDirExists         - FileorDir Exists
4. DeleteFolder            - Delete a given Folder
5. CopyFolder              - Copy a given Folder
6. GetallFilesinDir        - Get all Files from a directory
7. GetallSubdirsinDir      - Get all Subdirectories from a directory
8. FindReplaceinFile       - File / Replace all patterns in file
9. CountNumberofLines      - Counts number of lines of text file
internal static bool FileOrDirectoryExists(string name)
{
   return (Directory.Exists(name) || File.Exists(name));
}
internal static bool DirectoryExists(string name)
{
   return (Directory.Exists(name));
}
private void find_replace(string pattern, string pattern2, string file)
{
  string text = File.ReadAllText(file);
  text = text.Replace(pattern, pattern2);
  File.WriteAllText(file, text)
}