Solved

File.Delete  "The process cannot access the file ... because it is being used by another process."

Posted on 2014-10-17
8
1,662 Views
Last Modified: 2015-02-17
I'm having to maintain a C# program that is using File.WriteAllLines to write a file to disk.  I've needed to create at temp file to read back in and change some data based on data in another file read in.  

I want to delete the temp file when I leave so the user won't have the intermediate file to get confused with, but I get an error: "The process cannot access the file ... because it is being used by another process."

How do I "free" this intermediate file?  I don't see a Close method on File and nothing that I can find that sends back a handle that I could use to free or close that file I've written.

Thanks,
-- Jim Lowary
0
Comment
Question by:farminsure
  • 4
  • 3
8 Comments
 
LVL 32

Expert Comment

by:it_saige
ID: 40386693
What code are you using to manipulate the file (open, write, etc.)???  Is this file exclusive to this program only???

-saige-
0
 
LVL 16

Expert Comment

by:George Tokas
ID: 40386707
Check out the following from MS:
http://msdn.microsoft.com/en-us/library/b9skfh7s(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
It is for open() function but there are examples of the same functionality in C# and C++.
You will see that in C++ is using delete to free the file and in C# only the keyword using is needed to release the filestream object after finishing.
You can use a similar method.

George Tokas.
0
 

Author Comment

by:farminsure
ID: 40386767
Yes, the file is exclusive to this program.
The code I have File.WriteAllLines build the file

then to read it:

      public CSVReader(string filename, Encoding enc)
            : this(new FileStream(filename, FileMode.Open), enc) { }

        public string[] GetCSVLine()
        {
            string data = reader.ReadLine();
            if (data == null) return null;
            if (data.Length == 0) return new string[0];

            ArrayList result = new ArrayList();

            ParseCSVFields(result, data);      // puts the csv file into result array

            return (string[])result.ToArray(typeof(string));
        }
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40387598
I don't seem to have any problems reading back from a File.WriteAllLines().  There may be more that we are not seeing.

Here is the example code that I used:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FileExample
{
	class Program
	{
		static void Main(string[] args)
		{
			List<string> writer = new List<string>()
			{
				"1,2,3,4,5,6,7,8,9,10",
				"a,b,c,d,e,f,g,h,i,j",
				"10,9,8,7,6,5,4,3,2,1",
				"j,i,h,g,f,e,d,c,b,a"
			};
			File.WriteAllLines(@"c:\writealllines.txt", writer.ToArray());
			CSVReader readback = new CSVReader(@"c:\writealllines.txt", Encoding.ASCII);
			var Data = readback.GetCSVLines();
			foreach (var item in Data)
			{
				string line = string.Empty;
				foreach (var element in item)
					line += string.Format(" [{0}] ", element);
				Console.WriteLine(line);
			}
			Console.ReadLine();
		}
	}

	class CSVReader
	{
		FileInfo _file = null;
		Encoding _encoding = Encoding.Default;

		public CSVReader(string file, Encoding enc) : this(new FileInfo(file), enc) { ;}

		public CSVReader(FileInfo file, Encoding enc) { _file = file; }

		public IEnumerable<string[]> GetCSVLines()
		{
			if (_file.Exists)
			{
				string[] lines = File.ReadAllLines(_file.FullName, _encoding);
				if (lines.Length > 0)
				{
					foreach (string line in lines)
						yield return ParseCSVFields(line);
				}
			}
		}

		public string[] ParseCSVFields(string data)
		{
			return data.Split(',');
		}
	}
}

Open in new window


Produced the following output:Capture.JPG
With the following file created:Capture.JPG
-saige-
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:farminsure
ID: 40397709
I can read it back just fine the problem becomes when I close the program I want to delete the file and it give me the message;  "The process cannot access the file ... because it is being used by another process."

I was looking for a way of doing this with out totally redoing the program.
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40397944
There are a couple of reasons why you may not be able to delete the file.  Either, your FileStream still has the file open (you can get rid of this problem by way of a using statement) or because you don't have security access to the file (possible but highly unlikely as you created the file on the fly).

Amended above to include a File.Delete() -
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FileExample
{
	class Program
	{
		static void Main(string[] args)
		{
			List<string> writer = new List<string>()
			{
				"1,2,3,4,5,6,7,8,9,10",
				"a,b,c,d,e,f,g,h,i,j",
				"10,9,8,7,6,5,4,3,2,1",
				"j,i,h,g,f,e,d,c,b,a"
			};
			File.WriteAllLines(@"c:\writealllines.txt", writer.ToArray());
			CSVReader readback = new CSVReader(@"c:\writealllines.txt", Encoding.ASCII);
			var Data = readback.GetCSVLines();
			foreach (var item in Data)
			{
				string line = string.Empty;
				foreach (var element in item)
					line += string.Format(" [{0}] ", element);
				Console.WriteLine(line);
			}
			File.Delete(@"c:\writealllines.txt");
			Console.WriteLine(string.Format("The file I just created and reread exists? {0}", File.Exists(@"c:\writealllines.txt")));
			Console.ReadLine();
		}
	}

	class CSVReader
	{
		FileInfo _file = null;
		Encoding _encoding = Encoding.Default;

		public CSVReader(string file, Encoding enc) : this(new FileInfo(file), enc) { ;}

		public CSVReader(FileInfo file, Encoding enc) { _file = file; }

		public IEnumerable<string[]> GetCSVLines()
		{
			if (_file.Exists)
			{
				string[] lines = File.ReadAllLines(_file.FullName, _encoding);
				if (lines.Length > 0)
				{
					foreach (string line in lines)
						yield return ParseCSVFields(line);
				}
			}
		}

		public string[] ParseCSVFields(string data)
		{
			return data.Split(',');
		}
	}
}

Open in new window

Produces the following output -Capture.JPG
-saige-
0
 

Accepted Solution

by:
farminsure earned 0 total points
ID: 40606092
I just used a different file name a went on with project.  Did not have time to research further or do any rewrites.
Thanks for all suggestions.
0
 

Author Closing Comment

by:farminsure
ID: 40613804
Wasn't what I wanted but was what I had time to do.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video teaches viewers about errors in exception handling.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now