Introduction
If a group of files reside in a folder (directory) and a file in the group needs to be moved to another folder (directory) if a specific word is in the first line of the text file, then the file containing the specific word is moved leaving the remainder of the files without the specific word in the folder.
Background
Because I write code in LISP as part of using AutoCAD, I reviewed LISP files in a folder to determine if the LISP file worked. After testing the LISP file in AutoCAD and if the LISP code failed to execute (run) properly, I added the words "Doesn't" work in the first line of the LISP file. Because there were a large number of LISP files that I reviewed, 1,103 files, I didn't want to open each file to find the words "Doesn't" work and then move the file, I wrote a C# program to read the first line of each file which has the file name and a description of the purpose of the LISP code and then wrote the first line of the file to a text file. I printed the file to determine which files contained the words "Doesn't" work. Because there were about 200 to 300 files that contained the words, "Doesn't" work, and I didn't want to manually go through the list and move each file to another folder and manually mark the list as the file being moved, I wrote a C# program to move the files for me, by opening each file and looking at the first line of each LISP text file for the word "Doesn't" and if the word is in the first line, the file is moved to another folder.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace MF {
public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
string sourceDir = @"C:\VIDF\"; string destinDir = @"C:\VIDT\";
string[] files = Directory.GetFiles(sourceDir); foreach (string file in files) {
using (StreamReader readIt = new StreamReader
(sourceDir + Path.GetFileName(file))) {
string line = readIt.ReadLine(); if (line.Contains("DOESN'T")) {
File.Copy(file, destinDir + Path.GetFileName(file)); string holdName = sourceDir + Path.GetFileName(file); readIt.Close(); File.Delete(holdName); } readIt.DiscardBufferedData(); readIt.Close(); } }
Environment.Exit(0); } } }
Points of Interest
In developing this code, I could not find a reason the File.Move
did not work. The approach of copying the file and then deleting the first file was the only way to get the program to work.