Фрагмент кода должен был просто написать строку в текстовый файл «all_results.txt». У меня были ошибки в File.WriteAllText. После поиска сети для решений я попытался использовать FileStream и StreamWriter в качестве замены. Проблема все еще сохраняется.C# Процесс не может получить доступ к файлу '' ', потому что он используется другим процессом.
Это дало мне:
IOException Необработанное: Процесс не может получить доступ к файлу 'C: \ Users \ MadDebater \ Desktop \ ConsoleTest1 \ ConsoleTest \ Bin \ Debug \ all_results.txt', потому что он используется другим обработать.
Странно, ошибки возникают произвольно. Это может быть во время третьего цикла или 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
}
}
}
По какой причине вы не используете TextWriter? – w69rdy
Также я нашел ошибки, подобные этому в прошлом, при записи в текстовый файл в узком цикле. Файл не будет выпущен вовремя для следующей итерации, чтобы использовать его, и это может быть проблемой, особенно если есть много текста для записи. – w69rdy
@ w69rdy Не знаком с TextWriter. Существует ли решение проблемы с узким контуром? – youngscientist