文件被另一个进程访问

时间:2016-02-16 19:05:56

标签: c#

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

嗨大家和加尔斯, 使用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: 

本质上该文件已在使用中,但我无法弄清楚它的使用位置和使用方式。我尝试重新启动(因为我正在打开和关闭程序很多),我已经尝试删除重新制作文件。从我可以看到,抛出异常时没有其他StreamReaders / Writers打开,但Process Monitor显示了2个ViewerPoints.csv实例。

完整的代码在这里非常感谢:

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

        }
    }
编辑了

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

1 个答案:

答案 0 :(得分:4)

我会{\ _}}您的Stream对象触及该文件。

或者使用Dispose代替:

using

来自MS link

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