C# 进程无法访问文件“”因为它正在被另一个进程使用
代码片段只是应该将字符串写入名为“all_results.txt”的文本文件中。我在 File.WriteAllText 中实现时出错。在网上搜索解决方案后,我尝试使用 FileStream 和 StreamWriter 作为替代品。问题仍然存在。
它给了我:
IOException Unhandled: 该进程无法访问文件 'C:\Users\MadDebater\Desktop\ConsoleTest1\ConsoleTest\bin\Debug\all_results.txt',因为它正在被另一个进程使用。
奇怪的是,错误是任意发生的。它可能是在第 3 次循环期间或第 45 次循环期间发生错误。我提供了该类的完整代码,以防问题比看起来更严重。我确信这与我的病毒扫描程序或类似的东西无关。
try
{
using (FileStream stream = new FileStream(@"all_results.txt", FileMode.Create)) // Exception here
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(result);
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
即使我尝试这样做,它仍然失败。
try
{
File.WriteAllText(@"all_results.txt", result); // Exception here
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
以下是该类的完整代码。它的目的是接收 Twitter 推文列表,并使用贝叶斯分类将它们一一分类。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BayesClassifier;
using System.Text.RegularExpressions;
namespace ConsoleTest
{
class Analyzer
{
public static void Analyzing(List<string> all_results)
{
Reducting(all_results);
Classifying();
}
public static void Reducting(List<string> all_results)
{
//Reductor
//Precondition: List<string> results
all_results.ForEach(delegate(String text)
{
const string ScreenNamePattern = @"@([A-Za-z0-9\-_&;]+)";
const string HashTagPattern = @"#([A-Za-z0-9\-_&;]+)";
const string HyperLinkPattern = @"(http://\S+)\s?";
string result = text;
if (result.Contains("http://"))
{
var links = new List<string>();
foreach (Match match in Regex.Matches(result, HyperLinkPattern))
{
var url = match.Groups[1].Value;
if (!links.Contains(url))
{
links.Add(url);
result = result.Replace(url, String.Format(""));
}
}
}
if (result.Contains("@"))
{
var names = new List<string>();
foreach (Match match in Regex.Matches(result, ScreenNamePattern))
{
var screenName = match.Groups[1].Value;
if (!names.Contains(screenName))
{
names.Add(screenName);
result = result.Replace("@" + screenName,
String.Format(""));
}
}
}
if (result.Contains("#"))
{
var names = new List<string>();
foreach (Match match in Regex.Matches(result, HashTagPattern))
{
var hashTag = match.Groups[1].Value;
if (!names.Contains(hashTag))
{
names.Add(hashTag);
result = result.Replace("#" + hashTag,
String.Format(""));
}
}
}
// Write into text file
/*
try
{
using (FileStream stream = new FileStream(@"all_results.txt", FileMode.Create)) // Exception here
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(result);
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
*/
try
{
File.WriteAllText(@"all_results.txt", result); // Exception here
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
});
}
public static void Classifying()
{
// Classifying
BayesClassifier.Classifier m_Classifier = new BayesClassifier.Classifier();
m_Classifier.TeachCategory("Positive", new System.IO.StreamReader("POSfile.txt"));
m_Classifier.TeachCategory("Negative", new System.IO.StreamReader("NEGfile.txt"));
Dictionary<string, double> newscore;
newscore = m_Classifier.Classify(new System.IO.StreamReader("all_results.txt"));
PrintResults(newscore);
}
public static void PrintResults(Dictionary<string, double> newscore)
{
foreach (KeyValuePair<string, double> p in newscore)
{
Console.WriteLine(p.Key + ", " + p.Value);
}
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader("all_results.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line); // Add to list.
Console.WriteLine(line); // Write to console.
}
reader.Close();
}
//PrintSentiment(newscore);
}
public static void PrintSentiment(Dictionary<string, double> newscore)
{
// if difference < 2, neutral
// if neg < pos, pos
// if pos < neg, neg
double pos = newscore["Positive"];
double neg = newscore["Negative"];
string sentiment = "";
if (Math.Abs(pos - neg) < 1.03)
{
sentiment = "NEUTRAL";
}
else
{
if (neg < pos)
{
sentiment = "POSITIVE";
}
else if (pos < neg)
{
sentiment = "NEGATIVE";
}
}
Console.WriteLine(sentiment);
// append tweet_collection to final_results <string> list
// append sentiment tag to the final_results <string> list
// recursive
}
}
}
The snippet of code was just supposed to write a string into a text file called "all_results.txt". I had errors implementing in File.WriteAllText. After searching the net for solutions, I tried using FileStream and StreamWriter as substitutes. The problem still persists.
It gave me:
IOException Unhandled: The process cannot access the file 'C:\Users\MadDebater\Desktop\ConsoleTest1\ConsoleTest\bin\Debug\all_results.txt' because it is being used by another process.
Strangely, the errors occurs arbitrarily. It could be during the 3rd loop, or 45th loop before it hits an error. I provided the full code for that class in case the problem is deeper than it seems. I'm sure it has nothing to do with my virus scanner or anything like that.
try
{
using (FileStream stream = new FileStream(@"all_results.txt", FileMode.Create)) // Exception here
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(result);
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
Even when I try this, it still fails.
try
{
File.WriteAllText(@"all_results.txt", result); // Exception here
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
Below is the full code for the class. It is meant to take in a list of Twitter tweets and classify them using Bayes Classification one by one.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BayesClassifier;
using System.Text.RegularExpressions;
namespace ConsoleTest
{
class Analyzer
{
public static void Analyzing(List<string> all_results)
{
Reducting(all_results);
Classifying();
}
public static void Reducting(List<string> all_results)
{
//Reductor
//Precondition: List<string> results
all_results.ForEach(delegate(String text)
{
const string ScreenNamePattern = @"@([A-Za-z0-9\-_&;]+)";
const string HashTagPattern = @"#([A-Za-z0-9\-_&;]+)";
const string HyperLinkPattern = @"(http://\S+)\s?";
string result = text;
if (result.Contains("http://"))
{
var links = new List<string>();
foreach (Match match in Regex.Matches(result, HyperLinkPattern))
{
var url = match.Groups[1].Value;
if (!links.Contains(url))
{
links.Add(url);
result = result.Replace(url, String.Format(""));
}
}
}
if (result.Contains("@"))
{
var names = new List<string>();
foreach (Match match in Regex.Matches(result, ScreenNamePattern))
{
var screenName = match.Groups[1].Value;
if (!names.Contains(screenName))
{
names.Add(screenName);
result = result.Replace("@" + screenName,
String.Format(""));
}
}
}
if (result.Contains("#"))
{
var names = new List<string>();
foreach (Match match in Regex.Matches(result, HashTagPattern))
{
var hashTag = match.Groups[1].Value;
if (!names.Contains(hashTag))
{
names.Add(hashTag);
result = result.Replace("#" + hashTag,
String.Format(""));
}
}
}
// Write into text file
/*
try
{
using (FileStream stream = new FileStream(@"all_results.txt", FileMode.Create)) // Exception here
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(result);
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
*/
try
{
File.WriteAllText(@"all_results.txt", result); // Exception here
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
});
}
public static void Classifying()
{
// Classifying
BayesClassifier.Classifier m_Classifier = new BayesClassifier.Classifier();
m_Classifier.TeachCategory("Positive", new System.IO.StreamReader("POSfile.txt"));
m_Classifier.TeachCategory("Negative", new System.IO.StreamReader("NEGfile.txt"));
Dictionary<string, double> newscore;
newscore = m_Classifier.Classify(new System.IO.StreamReader("all_results.txt"));
PrintResults(newscore);
}
public static void PrintResults(Dictionary<string, double> newscore)
{
foreach (KeyValuePair<string, double> p in newscore)
{
Console.WriteLine(p.Key + ", " + p.Value);
}
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader("all_results.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line); // Add to list.
Console.WriteLine(line); // Write to console.
}
reader.Close();
}
//PrintSentiment(newscore);
}
public static void PrintSentiment(Dictionary<string, double> newscore)
{
// if difference < 2, neutral
// if neg < pos, pos
// if pos < neg, neg
double pos = newscore["Positive"];
double neg = newscore["Negative"];
string sentiment = "";
if (Math.Abs(pos - neg) < 1.03)
{
sentiment = "NEUTRAL";
}
else
{
if (neg < pos)
{
sentiment = "POSITIVE";
}
else if (pos < neg)
{
sentiment = "NEGATIVE";
}
}
Console.WriteLine(sentiment);
// append tweet_collection to final_results <string> list
// append sentiment tag to the final_results <string> list
// recursive
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
不要对 FileStream 和 StreamWriter 调用 Dispose() 和 Close(),这将由 using 子句自动处理。
Dont call Dispose() and Close() on the FileStream and StreamWriter, this will be handled automatically by the using-clause.
使用 filemon 等实用程序来检查哪些进程正在使用该文件。
更新:
据我了解,进程监视器与 filemon 非常相似。从这些工具中,您可以找到哪个进程在什么时候访问了您的文件。您可以在开始监控之前为您的文件添加过滤器。
您可以尝试的另一件事是锁定文件(如果存在)。
use a utility like filemon to check which processes are using the file.
UPDATE:
From what i read Process monitor is very much similar to filemon. from either of these tools you can find which process accessed your file at what point. you can add a filter for your file before you start monitoring.
the other thing you could try is to get a lock on the file if it exists.
也许该文件被病毒扫描程序或 Windows 索引服务访问?
Maybe the file is accessed by virus scanner or windows indexing service?
尝试将文件写入调试文件夹之外的另一个目录。
Try writing the file to another directory outside of the debug folder.
只是一个“狂野的镜头” - 如果您将文件放在更可预测的位置(例如“c:\all_results.txt”),会有帮助吗?
Just a "wild shot" - does it help if you place the file in a more predictable location like 'c:\all_results.txt'?
尝试将 Thread.Sleep(1000) 放入循环中。就像上面提到的那样,文件并不总是在循环的下一次迭代中及时释放。
try putting Thread.Sleep(1000) in your loop. Like someone mentioned above, the file doesn't always get released in time for the next iteration of the loop.
正如其他人所说,重复打开和关闭文件可能是问题所在。未提及的一种解决方案是在处理期间保持文件打开。完成后,可以关闭该文件。
As others have stated, opening and closing the file repeatedly might be the issue. One solution not mentioned is to keep the file open for the duration of the processing. Once complete, the file can be closed.
佩德罗:
或者,将文本收集到 StringBuilder 或其他内存中文本存储中,然后在循环完成后将文本转储到文件中。
Pedro:
Or, alternatively, collect your text in a StringBuilder or some other in-memory text storage and then dump the text to the file once the loop finishes.
我遇到类似问题时发现了该帖子。给出的建议给了我一个想法!因此,出于这个目的,我编写了以下方法
,然后按以下方式使用了该方法
后来分析日志,我发现我遇到麻烦的原因是尝试从并行线程对同一文件进行操作。但我仍然看到一些使用建议的故障转移方法的优点
I found the post while I had similar problem. The given advises gave me an idea! So for this purpose I wrote the following method
then I used the method in the following way
Later analyzing the logs I have discovered that the reason of my troubles was an attempt to act against the same file from the parallel threads. But I still see some pro-s in using the suggested FailOver method
尝试在文件操作周围使用锁定。
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Try using lock around your file operations.
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx