Hello,
I'm newer to programming and trying to do something that has me stumped. I need to read files from a directory on a server and compare those file names to a field in a database. When I find the file names that are the same, grab a different field which is actually a path to the server and see if the file exists there. If not, copy the file to that location. I've been working on this for quite some time, I have not started working on copying the files so I sort of want to try to figure that out on my own. But I need help in comparing the files, here is what I have so far...

namespace MissingImages
{
    public partial class frmImages : Form
    {
        public frmImages()
        {
            InitializeComponent();
        }

        private void btnGetDirFiles_Click(object sender, EventArgs e)
        {
            
                
               
                DirectoryInfo dirCustom = new DirectoryInfo("\\\\disk2\\images\\Missing Images");
            
                FileInfo[] filCustom;
               
                filCustom = dirCustom.GetFiles(); 
                
                
               
        }

        private void btnOBJTable_Click(object sender, EventArgs e)
       
        {
            SqlCommand cmd = new SqlCommand();

             {
                frmImages rd = new frmImages();
                rd.SimpleRead();
             }
        }

		public void SimpleRead()
		{
			
			SqlDataReader rdr = null;

			SqlConnection conn = new SqlConnection( "Server=TSQLTVS;UID=notreal;PWD=alsonotreal;Database=Flowtiva");

			SqlCommand cmd = new SqlCommand("select FILENAME, SOID from obj", conn);

			conn.Open();

			rdr = cmd.ExecuteReader();        		        
            
                       
     
        }

        
    }
}

This does appear as I step through it to pull the information from both places. The SOID field in the obj table of the database is just a string with the server path in it.

Can anyone help or at least point me in the right direction?

Thanks in advance

Recommended Answers

All 7 Replies

The basics are there but a few suggestions for you:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public class Program {
    private readonly string SERVER_PATH = @"\\server\directory";
    private readonly string LOCAL_PATH = @"C:\users\username\documents\images";
    private readonly string CONNECTION_STRING = "@some;sql=connection; string";

    [STAThread]
    public static int Main( string[ ] args ) {
        List<string> filesInDatabase = GetDatabaseFileName();
        List<string> filesOnServer = GetServerFileNames();

        foreach ( string fileName in filesOnServer ) {
            if ( !filesInDatabase.Contains(fileName) ) {
                // do copy code here which might look something like
                // the file names include the fullpath
                if ( File.Exists(fileName) ) {
                    try {
                        File.Copy(fileName, LOCAL_PATH + Path.GetFileName(fileName));
                    } catch ( Exception exception ) {
                        // Display some error notification here
                    }
                }
            }
        }
    }

    protected static List<string> GetDatabaseFileName( ) {
        List<string> returnValue = new List<string>();

        using ( SqlConnection connection = new SqlConnection(CONNECTION_STRING) ) {
            connection.Open();

            try {
                using ( SqlCommand command = connection.CreateCommand() ) {
                    command.CommandType = CommandType.Text;
                    command.CommandText = @"Place your SQL query here";

                    using ( SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection) ) {
                        while ( dataReader.Read() ) {
                            returnValue.Add(dataReader.GeString(0));
                        }
                    }
                }
            } catch ( Exception exception ) {
                throw exception;
            } finally {
                connection.Close();
            }
        }

        return returnValue;
    }

    protected static List<string> GetServerFileNames( ) {
        List<string> returnValue = new List<string>();

        if ( Directory.Exists(SERVER_PATH) ) {
            string[ ] files = Directory.GetFiles(SERVER_PATH);
            returnValue.AddRange(files);
        }

        return returnValue;
    }
}

Now, I wrote that in notepad, so if there's a misspelling or a parse error don't complain. :-)

Thanks to nvmobious but I'm still frustrated, however I do appreciate your help. (although it shows how much farther I have to go just to code simple things)

I don't think I adequately explained my problem, OR I'm too dumb to figure this out.

what I have is approx 15,000 images on one folder in the server - call it //disk2/images

and I have about 300,000 images in a database - call it imagedb

I need to take each image in the disk2 server images folder and search the imagedb until I find a match. When I find the match I have to grab the path that is attached to it so my query for that part has to have image and path in it. After images are matched then I have to check the patch to see if the file exists, if it does move on to the next and if it doesn't then copy the image from disk2 to the path that I grabed from the server and then move on to the next one.

if there is no match then I want to keep a log of that so I can manually check those images to find out what the problem is.

I've looked through the code and tried to use it, I tried to use my own code which I had figured out how to pull the image numbers locally and pull the image number from the database locally but I can't get the compare and copy to work...

How are you doing the file compare, it is entirely based on path + filename?

The file compare is just filenames - they are identical except the server files have the .tif extension but I can use the getwithoutextension to make them exact. The problem is when I find the match then I need to go to the pathname that the server has listed as where the file should actually be. Our system had a problem and we lost a bunch of the files from the server.
Our software reads the pathname from the database and points people to the file that is actually in the server to view it. But a bunch of those files are missing. I got a backup of the 15,000 images and need to put them in their proper place on the server.

Thanks for your help!

Assuming the user your running as has access to the remote server via a windows share, you can just use System.IO.File.Copy to move files. It's really that easy.
If you need to do FTP, it could be more difficult. If this is the case, I recommend move all the files locally into a folder, ziping the folder and using FTP to move the files up to the server where you can manually decompress them and fill in the gaps.

Thanks again for the help - I have successfully been able to do the compare - although it beat me up pretty good.

I wanted to post the code that I was able to get to work for the compare feature in case anyone else was looking (It's not pretty but works)

Now all I have to do is take the filename and change the name to the last part of the file path. (ie 00033569.TIF to 00001695) then I need to copy the file out to the file path.

I suppose I ought to back up the data first before changing the information so I don't lose it in case something breaks.

List<string> SOIDs;
        List<string> filesInDatabase = GetDatabaseFileName(out SOIDs);
       List<string> filesOnServer = GetServerFileNames();
       
        foreach ( string fileName in filesOnServer ) 
           
        {
            string fileOnly = Path.GetFileNameWithoutExtension(fileName).ToString();

            if ( filesInDatabase.Contains(fileOnly) ) 
            {
                
                int index = filesInDatabase.IndexOf(fileOnly);
                if (index >= 0)
                {
                    if ( !File.Exists(SOIDs[index]) ) 
                    {

                       
                        txtFiles.AppendText(fileOnly + "   " + SOIDs[index] + "\r\n");
                          
                       
                    }
                }
            }
        }
       
    }

    protected static List<string> GetDatabaseFileName( out List<string> SOID) 
    {
        List<string> returnValue = new List<string>();
        SOID = new List<string>();
        using ( SqlConnection connection = new SqlConnection(@"Server=TSQLTVS;UID=*****;PWD=**********;Database=Flowtiva")) 
        {
            connection.Open();

            
                using ( SqlCommand command = connection.CreateCommand() ) 
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = @"SQL query here";

                    using ( SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection) ) 
                    {
                        while ( dataReader.Read() ) 
                        {
                            returnValue.Add(dataReader.GetString(0));
                            
                            SOID.Add(dataReader.GetString(1));
                        }
                    }
                }
           
        }

        return returnValue;
        }

        protected static List<string> GetServerFileNames()
        {
            List<string> returnValue = new List<string>();

            if (Directory.Exists("\\\\disk2\\images\\Missing Images"))
            {
                string[] files = Directory.GetFiles("\\\\disk2\\images\\Missing Images");
              
                returnValue.AddRange(files);
               
            }
            return returnValue;

        }




    }

Good news, and the code doesn't look bad at all. Job well done. :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.