对于每个循环,请在第二个循环VB上停止

时间:2020-06-26 17:31:51

标签: vb.net for-loop foreach

我正在编写的软件正在计算机上安装的服务中运行。 我想读取一个文本文件,对其进行处理,并将其编码到其他路径。

该软件完全按照预期的方式运行,但仅处理2个文件,然后停止。我相信这与for每个循环有关。我在网上发现一些信息,说这与每个循环的每个循环分配的内存量有关。

感谢您的帮助。

我的代码是这样的。

For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Commsin\", FileIO.SearchOption.SearchTopLevelOnly, "ORDER-*.TXT")
      
            Dim filenum As Integer
            filenum = FreeFile()
            FileOpen(filenum, foundFile, OpenMode.Input)
            While Not EOF(filenum)

                <do a bunch of stuff> 
  
            End While

                <more code>

            Dim arrayFileName() As String = GetFileName.Split("\")
            Dim FileName As String = arrayFileName(2)

            My.Computer.FileSystem.CopyFile(foundFile, "C:\Commsin\Done\" & FileName)
            
            If IO.File.Exists("C:\Commsin\Done\" & FileName) Then
                My.Computer.FileSystem.DeleteFile(foundFile, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin)
                
                NoOfOrders -= NoOfOrders
            End If

Next

3 个答案:

答案 0 :(得分:0)

基本错误:请勿修改您要遍历的集合,即避免使用此模式(伪代码):

For Each thing In BunchOfThings:
   SomeOperation()
   BunchOfThings.Delete(thing)
Next thing

最好在此遵循此模式(再次使用伪代码):

While Not BunchOfThings.IsEmpty()
   thing = BunchOfThings.nextThing()
   SomeOperation()
   BunchOfThings.Delete(thing)
End While

我将保留它作为练习,让您将代码从第一种方法转换为第二种方法。

答案 1 :(得分:0)

您似乎正在尝试使用Split()从完整路径中提取文件名。

为什么不只使用:

Dim fileName As String = IO.Path.GetFileName(foundFile)

代替:

Dim arrayFileName() As String = GetFileName.Split("\")
Dim FileName As String = arrayFileName(2)

答案 2 :(得分:0)

谢谢大家,对于我的建议,我已经成功实施了建议的更改。原来,问题不在于代码本身。

与我正在使用的其中一个文件一起,有一个文本行,该文本行一旦拆分成一个数组,就没有指定的长度,给出错误“索引超出数组范围”。

这是文件上的错误,我还添加了一些检查以防止将来出现此错误。 谢谢。

相关问题