[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 494
  • Last Modified:

mylog file is being used by another process?

Hi,
When I click the button, it calls MyWorld method.
As u can see, MyWorld() checks if 'mylog.txt' is in the path.  If it isn't, it should be created.
Then, it calls YourMethod in Class1.

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            MyWorld();
        }
        private void MyWorld()//<--this is in Form1.
        {  
            string mylogpath = "D:\\mylog.txt";
            if (File.Exists(mylogpath) == false)
            {
                File.Create(mylogpath);
            }                    
            Class1.YourMethod( mylogpath, this); //<--YourMethod is in Class1 class.    
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WindowsFormsApplication1
{
    static class Class1
    {
        public static void YourMethod(string logpath, Form1 f1)
        {
            string str = f1.textBox1.Text + "\n";
            StreamWriter sw = File.AppendText(logpath);
            string mystr = str + "\n";
            sw.WriteLine(mystr);
            sw.WriteLine();
            sw.Close();
        }

    }
}

When I click the button, the error displays "The process cannot access the file 'D:\\mylog.txt' because it is being used by another process.
This is happening only when there is no mylog.txt in the path.  Where there is mylog.txt in the path, it works fine.

What's the problem?  what should I fix here?
     
0
IzzyTwinkly
Asked:
IzzyTwinkly
  • 3
1 Solution
 
Jens FiedererCommented:
Your "Create" is opening a new FileStream.  Close that.
0
 
Jens FiedererCommented:
FileStream stream = File.Create(mylogpath);
if (stream != null)
{
         stream.Close();
}

0
 
IzzyTwinklyAuthor Commented:
What a valuable lesson u taught me! =)
0
 
Jens FiedererCommented:
How gracious!  
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now