0

There is a file in my application. I want to use this file to write data(which is coming from a machine connected on LAN) as well as for reading data from it and writing in a database. Therefore, I am placing a condition to check if the file is free.

This is my code:

static public bool IsFileFree(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {        
        return false;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
       return true;
}

static public void dataread()
{
    FileInfo info = new FileInfo("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
    while (true)
    {
        if (IsFileFree(info) == true)
        {
            byte[] bytesFrom = new Byte[1000];
            Program.socarray[0].Receive(bytesFrom);
            char[] stuffed = System.Text.Encoding.UTF8.GetString(bytesFrom).ToCharArray();
            char[] final;
            final = stuffed.ToArray();
            string foo = new string(final);
             System.IO.File.WriteAllText(@"C:\Users\cdac\Desktop\server\server\TextFile2.txt", foo);
            System.Threading.Thread.Sleep(10);
        }
        else
        {
            MessageBox.Show("File is already ", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
        }
    }
}


static public void datawrite()
{
    FileInfo info = new FileInfo("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
    while (true)
    {
        if (IsFileFree(info) == true)
        {
            string MyConString = "server=localhost;" +
                                 "database=cdac;" +
                                 "User Id=root;" + 
                                 "password=cdac56;";
            MySqlConnection connection = new MySqlConnection(MyConString);
            MySqlCommand command = connection.CreateCommand();
            MySqlDataReader Reader;
            connection.Open();

            // StreamReader reader = new StreamReader("C:\\tag_log_030610.txt");
            StreamReader reader = new StreamReader("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] parts = line.Split(';');
                //command.CommandText = "insert into st_attn(rollno,Th_attn,Name) values('" + parts[0] + "','" + parts[1] + "','" + parts[2] + "')";

                command.CommandText = "insert into st_attn(rollno,Name) values('"  +   parts[0] + "','" + parts[1] + "')";

                Reader = command.ExecuteReader();
            }
            System.Threading.Thread.Sleep(10);
        }
        else
        {
            MessageBox.Show("File is already in use", "My Application",
            MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
        }
    }
 }

 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     int i=0;
     TcpListener listener = new TcpListener(8888);

     listener.Start();

     while(true)
     {
         Socket soc = listener.AcceptSocket();
         socarray[i] = soc;
         i++;
         if (i == NUMBEROFREADERS)
             break;

     }

     Thread writetotextfile = new Thread(dataread);
     writetotextfile.Start();


     Thread writetodatabase = new Thread(datawrite);
     writetodatabase.Start();


     Application.Run(new Form1());
}

When i execute it, my application is not writing anything in textfile and the data which is already existing in this text file is being written in the database with every execution or this application.

I want my application to write data in the text file which is not being written by it currently. Moreover both the processes( one that is for writing data in text file and other for writing data in DB from text file) when make conflict i want to give preference to one which is writing data in text file and want the other process to wait till then. And as soon as data is written in text file and it is free, the data is to be written in database from text file.

avneet
  • 3
  • 4
  • 1
    So what is your question? What should happen that isn't going as you've expected? – Matthijs Aug 07 '14 at 06:24
  • I want my application to write data in the text file which is not being written by it currently. Moreover both the processes( one that is for writing data in text file and other for writing data in DB from text file) when make conflict i want to give preference to one which is writing data in text file and want the other process to wait till then. And as soon as data is written in text file and it is free, the data is to be written in database from text file. – avneet Aug 07 '14 at 06:30
  • Edit your question with this information ;) – Matthijs Aug 07 '14 at 06:34
  • If you're looking for threadsafety, this won't do. What if between Thread 1 checking if the file is free and actually accessing it, Thread 2 jumps in and takes posession of the file? Or the file get's deleted from the outside or whatever. How about `try { File.WriteAllText(path, content, encoding); } catch (Exception ex) { handleNotAbleToWrite(); }`? Or better yet react to specific Exceptions in specific ways. -- BTW. if all this happens in the same application, you can [lock](http://msdn.microsoft.com/library/c5kehkcz.aspx) the file access. – Corak Aug 07 '14 at 06:34
  • Can you not write your data to the database and text file in one pass, rather then caching via the file first? Same net result but without the same thread complexity. – kidshaw Aug 07 '14 at 06:40
  • data will be coming from a remote machine and is not to be pushed directly in a database – avneet Aug 07 '14 at 06:44
  • Other than that, you use exceptions to control the flow of your software, which is a [bad idea](http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control). -- "is not to be pushed directly in a database" - why not? You could have a very simple queue table (first in, first out), where you temporarily store the information you get from the remote machine until you're able to write it into the actual destination (`st_attn`). – Corak Aug 07 '14 at 06:48
  • While I am debugging the above code, the parts of the two functions (dataread and datawrite) are not being executed. The parts where condition is checked that whether file is free on not is not executed. It seems that the file is not free. What shall I do?? – avneet Aug 13 '14 at 06:39

0 Answers0