【问题标题】:How can I pull the most recent file dropped into a folder and loop through each line in the file?如何将最新的文件拖放到文件夹中并循环遍历文件中的每一行?
【发布时间】:2023-02-26 04:27:56
【问题描述】:

过去两天我一直在处理我的代码,但一直出错。可以,我有帮助吗?

代码背景

我创建了一个 QR 代码生成器,它成功地监视了一个文件夹,以查看何时将新文件放入该文件夹 (FileSystemWatcher)。

当一个新文件被删除时,一个事件处理程序被触发,它将拉取文件夹中的最新文件并逐行读取它的每一行。对于文件中的每一行,将生成一个单独的二维码并保存在另一个文件夹中。

问题:

我不知道如何为每一行生成二维码。当我尝试读取文件夹中最新文件的每一行时,出现错误:“System.IO.IO.Exception:进程无法访问文件,因为它正被另一个进程使用。”

除了我循环遍历文件中的每一行之外,一切正常(成功监控文件夹、提取最新文件、生成二维码并保存图像)。

当新文件添加到文件夹时触发我的事件处理程序:


`  private static void OnChanged(object source, FileSystemEventArgs e)     // Specify action when file added
        {
            string FileLine = null;
            Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);

            var file = new DirectoryInfo(@"C:\Users\Desktop\BarCodeData\").GetFiles().OrderByDescending(o => o.CreationTime).FirstOrDefault();
            string FilePath = file.DirectoryName;
            string Filename = file.Name;
            string FileName = FilePath +"\\"+ Filename;            //Sets the FileName to the most recent file added paths.

            StreamReader ReaderObject = new StreamReader(FileName);

            // ReaderObject reads a single line, stores it in Line string variable and then displays it on console
            while ((FileLine = ReaderObject.ReadLine()) != null)
            {
                Bitmap bmap = QR.Encoder(FileLine);      //creates the QR code from the data in the files line

                QR.SaveImage(bmap, FileLine, @"C:\Users\Desktop\BarCodeImages\");         //saves QR image to a folder.

            }

        }`

当我到达“StreamReader ReaderObject = new StreamReader(FileName)”时,我得到了抛出的异常。它成功地抓取了最新的文件,并将其设置为 FileName,但无法读取文件中的每一行。

【问题讨论】:

    标签: c# loops file monitoring streamreader


    【解决方案1】:

    您需要确保在读取文件后关闭 StreamReader,以便其他进程可以访问它。您可以通过将它包装在 using 语句中来实现,当您使用完它时,它会自动释放该对象。

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
    
        var file = new DirectoryInfo(@"C:UsersDesktopBarCodeData").GetFiles().OrderByDescending(o => o.CreationTime).FirstOrDefault();
        var FilePath = file.DirectoryName;
        var Filename = file.Name;
        var FileName = FilePath + "\" + Filename;
    
        using var ReaderObject = new StreamReader(FileName);
        while ((FileLine = ReaderObject.ReadLine()) != null)
        {
            Bitmap bmap = QR.Encoder(FileLine);
            QR.SaveImage(bmap, FileLine, @"C:UsersDesktopBarCodeImages");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 2014-10-04
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多