对于目录goto子例程中的每个文件 [英] for each file in directory goto sub routine

查看:71
本文介绍了对于目录goto子例程中的每个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的问题,但我似乎无法弄清楚如何编码它。我知道我希望它遵循的逻辑。



我编写了一个程序,通过tcp端口接收文本,并进行格式化,一旦格式化,就会创建一个文本框并且文本被附加到文本框中。



显然,如果我关闭程序,那些文本框和信息将会消失,所以我重新编程了程序的流程,所以一次它接收所有数据,在做任何其他事情之前它将这些文件保存到目录。



form_load我想搜索目录,然后搜索每个文件读取后会通过子程序进行格式化和文本框创建。



我想不出怎样才能正确地做到这一点。



在我脑海里它基本上是这样的。



This is probably a real easy one, but I can't seem to work out how to code it. I know the logic I want it to follow though.

I have written a program that receives text via tcp port, and is formatted, and once formatted a textbox is created and the text is appended to the textbox.

Obviously if I close the program, those textboxes and information will disappear, so I have reprogrammed the flow of the program so once it receives all of the data, prior to doing anything else it saves those files to a directory.

on form_load I want to search the directory, and then for each file that is read go through the sub routines for formatting, and textbox creation.

I just can't think of how to do this correctly.

in my head it is basically like this.

for each "file" in "directory"
         file.text = datastring
         file.name = filename
         currenttb = currenttb
       createtxtbox(datastring filename, currenttb)
next

推荐答案

你离我太远了。以下工作原理

You're not too far off. The following would work
'You will need Imports System.IO

'These can be stored in config or passed as parameters
Const folderName As String = "c:\temp"
Const searchPattern As String = "*.txt"

Dim fileNames As String() = Directory.GetFiles(folderName, searchPattern)

'For Each f As String In fileNames 
'You can use For Each if you don't want to use the counter - see below
For i As Long = 0 To fileNames.GetUpperBound(0)
    createtxtbox(fileNames(i), i)
Next



那么子例程可能看起来像这样


Then the sub-routine could look something like this

Private Sub createtxtbox(ByVal fileName As String, ByVal i As Long)

    Dim newTxtBox As TextBox = New TextBox()

    newTxtBox.Name = i.ToString()
    newTxtBox.Multiline = True
    newTxtBox.ScrollBars = ScrollBars.Both

    'You'll need to position the text box in some way - I've used the file "number"
    newTxtBox.Top = (i * 20) + 1
    newTxtBox.Left = (i * 20) + 1

    newTxtBox.Text = File.ReadAllText(fileName)
    Me.Controls.Add(newTxtBox)

End Sub



你应该包含一些try-catch异常检查无论您的格式要求是什么。



注意我使用 ReadAllText 只是为了将整个文件作为单个字符串,如果你想逐行使用 ReadAllLines 而是用 For Each 循环遍历内容或对于循环


You should include some try-catch exception checking and whatever your formatting requirements are.

Note I used ReadAllText just to get the entire file as a single string, if you want to get it line-by-line use ReadAllLines instead and loop through the contents with a For Each or For loop


这篇关于对于目录goto子例程中的每个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆