C# 另一进程正在访问的文件

C# 另一进程正在访问的文件,c#,C#,免责声明:已经通过几个类似的线程没有成功 大家好, 正在使用Twitch.tv聊天机器人,并遇到IOStreams问题。我有一个文件(ViewerPoints.csv),我存储了一些在频道中花费时间的任意点,这些点将用于我以后要编程的迷你游戏。现在,StreamReader/StreamWriter的每个实例在下一个实例访问它之前都与.Close()配对,但是我得到以下错误: System.IO.IOException was unhandled HResult=-2147024864

免责声明:已经通过几个类似的线程没有成功

大家好, 正在使用Twitch.tv聊天机器人,并遇到IOStreams问题。我有一个文件(ViewerPoints.csv),我存储了一些在频道中花费时间的任意点,这些点将用于我以后要编程的迷你游戏。现在,StreamReader/StreamWriter的每个实例在下一个实例访问它之前都与.Close()配对,但是我得到以下错误:

System.IO.IOException was unhandled
  HResult=-2147024864
  Message=The process cannot access the file 'S:\Programming\Projects\C#\StarBot\StarBot\bin\Debug\ViewerPoints.csv' because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
       at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
       at System.IO.StreamWriter..ctor(String path, Boolean append)
       at StarBot.Program.assignPoints() in S:\Programming\Projects\C#\StarBot\StarBot\Program.cs:line 156
       at StarBot.Program.Main(String[] args) in S:\Programming\Projects\C#\StarBot\StarBot\Program.cs:line 40
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
基本上,该文件已经在使用中,但我不知道它在哪里被使用,被什么人使用。我尝试过重新启动(因为我经常打开和关闭程序),我尝试过删除一个文件并重新制作文件。从我所看到的情况来看,当引发异常时,没有其他StreamReader/Writer打开,但流程监视器显示了ViewerPoints.csv的2个实例

这里提供了完整的代码,非常感谢您的帮助:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Net;

    namespace StarBot
    {
        class Program
        {
            private static DateTime time;
            private static double messageDelay = 30.0;
            private static DateTime nextMessage = DateTime.UtcNow.AddSeconds(messageDelay);
            private static string[] viewerArray;
            private static string ViewerPointsFile = "ViewerPoints.csv";
            static void Main(string[] args)
            {
                //password from www.twitchapps.com/tmi
                //include "oauth:" portion
                IRCClient irc = new IRCClient("irc.twitch.tv", 6667, "Star__Bot", "oauth:likeidreallyleavethiskeyinhere");
                irc.joinRoom("dystarplays");
                getViewers();
                irc.sendChatMessage("Star__Bot Connected...");
                while (true)
                {
                    time = DateTime.UtcNow;
                    string message = irc.readMessage();
                    if(message!= null)
                    {
                        if (message.IndexOf('*') >= 0)
                        {
                            irc.sendChatMessage(processMessage(message));
                        }
                    }

                    if(time >= nextMessage)
                    {
                        assignPoints();
                        //print message from list
                        nextMessage = time.AddSeconds(messageDelay);

                    }
                }
            }

            private static void assignPoints()
            {
                getViewers();
                StreamReader sr = new StreamReader(ViewerPointsFile);
                StringBuilder sb = new StringBuilder();
                string viewerPointsFile = sr.ReadToEnd();
                sr.Close();
                int points;
                string spoints;
                viewerPointsFile = viewerPointsFile.Replace("\r\n", ",");
                viewerPointsFile = viewerPointsFile.Remove(viewerPointsFile.Length - 1, 1);
                string[] viewerPoints = viewerPointsFile.Split(',');
                for (int i = 0; i< viewerPoints.Length; i= i + 2)
                {
                    string viewerInFile = viewerPoints[i];
                    bool added = false;
                    foreach (string viewerInChannel in viewerArray)
                    {
                        if (viewerInFile.ToLower() == viewerInChannel.ToLower())
                        {
                            spoints = viewerPoints[Array.IndexOf(viewerPoints, viewerInFile) + 1];
                            points = int.Parse(spoints);
                            sb.Append(viewerInChannel + "," + ++points + "\r\n");
                            added = true;
                        }
                    }
                    if (!added)
                    {
                        spoints = viewerPoints[Array.IndexOf(viewerPoints, viewerInFile) + 1];
                        points = int.Parse(spoints);
                        sb.Append(viewerInFile + "," + points + "\r\n");
                    }
                }
//error happens on the StreamWriter here
                StreamWriter sw = new StreamWriter(ViewerPointsFile);
                spoints = sb.ToString();
                sw.Write(spoints);
                sw.Close();

            }

            private static string getPoints(string user)
            {
                StreamReader sr = new StreamReader(ViewerPointsFile);
                string line;
                while ((line = sr.ReadLine().ToLower())!= null)
                {
                    if (line.IndexOf(user) >= 0)
                    {
                        return line.Replace(",",": ");
                    }
                }
                sr.Close();
                return user + ": 0";
            }

        }
    }
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.IO;
Net系统;
名称空间StarBot
{
班级计划
{
私有静态日期时间;
私有静态双消息延迟=30.0;
私有静态DateTime nextMessage=DateTime.UtcNow.AddSeconds(messageDelay);
私有静态字符串[]viewerArray;
私有静态字符串ViewerPoints file=“ViewerPoints.csv”;
静态void Main(字符串[]参数)
{
//来自www.twitchaps.com/tmi的密码
//包括“oauth:”部分
IRCClient irc=new-IRCClient(“irc.twitch.tv”,6667,“Star\uu Bot”,“oauth:likeidreallyleavethiskeyinhere”);
irc.joinRoom(“Dysarplays”);
getViewers();
发送聊天信息(“星型机器人连接…”);
while(true)
{
时间=DateTime.UtcNow;
string message=irc.readMessage();
如果(消息!=null)
{
如果(message.IndexOf('*')>=0)
{
sendChatMessage(processMessage(message));
}
}
如果(时间>=下一条消息)
{
赋值点();
//从列表打印邮件
nextMessage=time.AddSeconds(messageDelay);
}
}
}
私有静态无效赋值点()
{
getViewers();
StreamReader sr=新的StreamReader(ViewerPointsFile);
StringBuilder sb=新的StringBuilder();
字符串viewerPointsFile=sr.ReadToEnd();
高级关闭();
积分;
弦点;
viewerPointsFile=viewerPointsFile.Replace(“\r\n”,“,”);
viewerPointsFile=viewerPointsFile.Remove(viewerPointsFile.Length-1,1);
字符串[]viewerPoints=viewerPoints文件.Split(',');
对于(int i=0;i=0)
{
返回行。替换(“,”,“:”);
}
}
高级关闭();
返回用户+“:0”;
}
}
}

[编辑]编辑以删除不必要的代码。

我将
处理与文件接触的流对象

或者使用
而不是像以下那样使用

using StreamWriter sw = new StreamWriter(ViewerPointsFile)
    {
       spoints = sb.ToString();
       sw.Write(spoints);
    }
引自

关闭方法:
“关闭当前流并释放与当前流关联的任何资源(如套接字和文件句柄)。不要调用此方法,而是确保流已正确处理”

要发布的代码太多了。。你能准确地指出代码中发生这种情况的地方并用相关信息更新问题吗?我们没有时间通读你的所有代码/代码审查,尤其是在它不起作用的情况下。@MethodMan:删除不必要的代码并添加注释以突出显示错误所在的行thrown@Dystar有什么价值
ViewerPoints文件
在出现异常时?它具有topAgree中定义的“ViewerPoints.csv”,但调用Close是相同的。最好使用
使用