当前位置: 首页 > 知识库问答 >
问题:

IOException进程无法访问该文件,因为在使用XDocument时,另一个进程正在使用该文件

商开济
2023-03-14

我不断收到一个IOException,它无法访问该文件,因为它正被另一个进程使用。我想做的是每次我查看的文件都会被更改。。它通过TCP/IP以数组的形式发送。我找不到任何关闭XDocument的方法,只是不知道如何修复这个错误。。。我用谷歌搜索了一下,但还是什么都找不到。任何帮助都将不胜感激

编辑:我发现了其他的解决方案与fileereader和其他东西...但它似乎不同,当使用xfile

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

//filesystemwatcher
using System.IO;

//tcpip server
using System.Net;
using System.Net.Sockets;

//XML
using System.Xml;
using System.Xml.Linq;

namespace ChampSelect_FileWatcher
{
    class Program
    {
        //TCP IP variables
        public static Int32 port;
        public static IPAddress localAddr;
        public static TcpListener server;
        public static TcpClient client;
        public static NetworkStream stream;
        public static XDocument doc;


        public static void Main(string[] args)
        {
            //LOAD XML FILE
            doc = XDocument.Load("C:/Trio Scripts/example.xml");

            //OBSERVE FILE
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"C:\Trio Scripts";
            watcher.Filter = "example.xml";

            //watch for changes in LastWrite
            watcher.NotifyFilter = NotifyFilters.LastWrite;

            //event handler
            watcher.Changed += new FileSystemEventHandler(OnChanged);

            //Begin watching
            watcher.EnableRaisingEvents = true;


            //TCP IP SERVER
            try
            {
                Console.WriteLine("Waiting for 99150 to run...\n");
                //config TCP stuff
                port = 9905;
                localAddr = IPAddress.Parse("10.0.0.66");
                server = new TcpListener(localAddr, port);
                server.Start();
                client = server.AcceptTcpClient();
                stream = client.GetStream();
                Console.WriteLine("Connection to Viz successful!");
                Console.WriteLine("***LISTENING FOR CHANGES TO: " + watcher.Filter + "***\n");


            }
            catch (SocketException z)
            {
                Console.WriteLine("SocketException: {0}", z);
            }

            //prevent console from closing
            Console.ReadKey();
            Console.ReadKey();
            Console.ReadKey();
        }

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            //reload xml file
            //doc = XDocument.Load("C:/Trio Scripts/example.xml");
            //doc.Root.ReplaceWith(XElement.Load("C:/Trio Scripts/example.xml"));

            XDocument doc;
            using (var reader = XmlReader.Create("C:/Trio Scripts/example.xml"))
            {
                doc = XDocument.Load(reader);
            }

            // Nodes in XML
            string[] bans = doc.Descendants("ban").OrderBy(element => Int32.Parse(element.Attribute("order").Value)).Select(element => element.Value).ToArray();

            // String to send the message on
            String sendMsg = "";

            // Proceed with reading XML
            for (int i = 0; i < bans.Length; i++)
                sendMsg += bans[i] + " ";

            byte[] msg = System.Text.Encoding.ASCII.GetBytes(sendMsg);
            stream.Write(msg, 0, msg.Length);
            Console.WriteLine("Change detected, sending changes to Viz");
            sendMsg = "";
        }
    }//end class
}//end namespace

共有2个答案

夏飞跃
2023-03-14

您仍然可以使用X文档XmlReader

XDocument doc;
using (var reader = XmlReader.Create("C:/Trio Scripts/example.xml"))
{
    doc = XDocument.Load(reader);
}

当读取器使用块的完成时,应该关闭文件句柄。

更新:

可能是XmlReader的行为。Create(string)不会以最简单的方式打开文件。如果这就是导致异常的原因,请尝试以下更明确的代码来指定文件权限:

XDocument doc;
using (var stream = File.Open("C:/Trio Scripts/example.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = XmlReader.Create(stream))
{
    doc = XDocument.Load(reader);
}

范浩荡
2023-03-14

问题是,每当文件发生更改时,就会出现多个更改事件。

在读取更改的文件之前,您应该等待一段时间。

您还应该使用e.FullPath并检查

 e.ChangeType == WatcherChangeTypes.Changed

如果无法打开文件,请稍后再试。

 类似资料: