?
Solved

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

Posted on 2014-10-17
8
Medium Priority
?
2,355 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 34

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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 34

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
 

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 34

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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Suggested Courses

762 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