因为它正由另一个进程使用C#进程无法访问该文件''' [英] C# The process cannot access the file ''' because it is being used by another process

查看:227
本文介绍了因为它正由另一个进程使用C#进程无法访问该文件'''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code的片段只是应该写一个字符串到一个名为all_results.txt的文本文件。我曾在File.WriteAllText执行错误。搜索网的解决方案后,我尝试使用的FileStream和StreamWriter作为替代品。问题仍然存在。

它给了我:

IOException异常未处理:该进程无法访问该文件。C:\\用户\\ MadDebater \\桌面\\ ConsoleTest1 \\ ConsoleTest \\ BIN \\调试\\ all_results.txt',因为它正被另一个进程使用

奇怪的是,随意发生的错误。这可能是第3次循环或45循环期间它击中错误之前。我公司提供的全code该类案件中的问题的深度超过它似乎。我敢肯定,这无关我的病毒扫描程序之类的东西。

 尝试
                {
                    使用(的FileStream流=新的FileStream(@all_results.txt,FileMode.Create))//这里异常
                {
                    使用(StreamWriter的作家=新的StreamWriter(流))
                    {
                        writer.WriteLine(结果);
                        writer.Dispose();
                        writer.Close();
                    }                    stream.Dispose();
                    stream.Close();
                }                }
                赶上(IOException异常前)
                {
                    Console.WriteLine(除息);
                }

甚至当我尝试这一点,它仍然失败。

 尝试
                {
                    File.WriteAllText(@all_results.txt,结果); //这里异常
                }
                赶上(IOException异常前)
                {
                    Console.WriteLine(ex.Message);
                }

以下是完整code为类。它的目的是采取Twitter的微博列表,并使用贝叶斯分类逐一分类。

 使用系统;
    使用System.IO;
    使用System.Collections.Generic;
    使用System.Linq的;
    使用System.Text;
    使用BayesClassifier;
    使用System.Text.RegularEx pressions;    命名空间ConsoleTest
    {
        类分析仪
        {
            公共静态无效分析(表<串GT; all_results)
            {            Reducting(all_results);
            判断();
        }        公共静态无效Reducting(列表<串GT; all_results)
        {
            //减速机
            // precondition:列表<串GT;结果
            all_results.ForEach(委托​​(字符串文本)
            {                常量字符串ScreenNamePattern = @@([A-ZA-Z0-9 \\ -_&放;;] +);
                常量字符串HashTagPattern = @#([A-ZA-Z0-9 \\ -_&放;;] +);
                常量字符串HyperLinkPattern = @(HTTP:// \\ S +)\\ s?
                字符串结果=文本;                如果(result.Contains(HTTP://))
                {
                    VAR链接=新的List<串GT;();
                    的foreach(在Regex.Matches比赛比赛(结果,HyperLinkPattern))
                    {
                        VAR URL = match.Groups [1] .value的;
                        如果(!links.Contains(URL))
                        {
                            links.Add(URL);
                            结果= result.Replace(URL,的String.Format());
                        }
                    }
                }                如果(result.Contains(@))
                {
                    VAR名=新的List<串GT;();
                    的foreach(在Regex.Matches比赛比赛(结果,ScreenNamePattern))
                    {
                        VAR屏幕名= match.Groups [1] .value的;
                        如果(!names.Contains(屏幕名))
                        {
                            names.Add(屏幕名);
                            结果= result.Replace(@+屏幕名,
                               的String.Format());
                        }
                    }
                }                如果(result.Contains(#))
                {
                    VAR名=新的List<串GT;();
                    的foreach(在Regex.Matches比赛比赛(结果,HashTagPattern))
                    {
                        VAR HASHTAG = match.Groups [1] .value的;
                        如果(!names.Contains(包括hashtag))
                        {
                            names.Add(包括hashtag);
                            结果= result.Replace(#+#标签,
                               的String.Format());
                        }
                    }
                }                //写入文本文件
/ *
                尝试
                {
                    使用(的FileStream流=新的FileStream(@all_results.txt,FileMode.Create))//这里异常
                {
                    使用(StreamWriter的作家=新的StreamWriter(流))
                    {
                        writer.WriteLine(结果);
                        writer.Dispose();
                        writer.Close();
                    }                    stream.Dispose();
                    stream.Close();
                }                }
                赶上(IOException异常前)
                {
                    Console.WriteLine(除息);
                }
                * /
                尝试
                {
                    File.WriteAllText(@all_results.txt,结果); //这里异常
                }
                赶上(IOException异常前)
                {
                    Console.WriteLine(ex.Message);
                }            });
        }        公共静态无效的分类()
        {
            //分类            BayesClassifier.Classifier m_Classifier =新BayesClassifier.Classifier();
            m_Classifier.TeachCategory(正,新的就是System.IO.StreamReader(POSfile.txt));
            m_Classifier.TeachCategory(负,新的就是System.IO.StreamReader(NEGfile.txt));            字典<字符串,双> newscore;
            newscore = m_Classifier.Classify(新就是System.IO.StreamReader(all_results.txt));            PrintResults(newscore);
}        公共静态无效PrintResults(词典<字符串,双> newscore)
        {
            的foreach(KeyValuePair<字符串,双指p在newscore)
            {
                Console.WriteLine(p.Key +,+ p.Value);
            }            清单<串GT;名单=新名单,LT;串>();
            使用(StreamReader的读者=新的StreamReader(all_results.txt))
            {
                串线;
                而((行= reader.ReadLine())!= NULL)
                {
                    list.Add(线); // 添加到列表。
                    Console.WriteLine(线); //写入控制台。                }                reader.Close();
            }            // PrintSentiment(newscore);
        }        公共静态无效PrintSentiment(词典<字符串,双> newscore)
        {            //如果差< 2,中性
            //如果NEG< POS机,POS机
            //如果pos<负,负            双POS = newscore [积极];
            双负= newscore [负面];
            字符串情绪=;            如果(Math.Abs​​(正 - 负)LT; 1.03)
            {
                情绪=中性;
            }
            其他
            {
                如果(NEG< POS)
                {
                    情绪=阳性;
                }
                否则,如果(POS&L​​T;负)
                {
                    情绪=负面;
                }
            }            Console.WriteLine(情绪);
            //追加tweet_collection到final_results<串GT;名单
            //情绪标签附加到final_results<串GT;名单
            //递归
        }
    }
}


解决方案

不要调用Dispose()和close()上的FileStream和StreamWriter,这将自动被使用子句来处理。

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
        }
    }
}

解决方案

Dont call Dispose() and Close() on the FileStream and StreamWriter, this will be handled automatically by the using-clause.

这篇关于因为它正由另一个进程使用C#进程无法访问该文件'''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆