【问题标题】:vb.net can read\ open or save file because of file name issue由于文件名问题,vb.net 可以读取\打开或保存文件
【发布时间】:2013-05-22 09:43:05
【问题描述】:

我正在尝试编辑我的代码以打开文件夹 ATC 中的所有文件(包括任何子目录)

如果发现这些文件中的任何一个不包含文本“索引...”,则附加该特定文件以包含在文档“C:\stuff.txt”中找到的文本,然后保存包含更改的文件...

我遇到的问题是文件名。

第一个问题是我的 TARGET_FILE 打不开;第二个问题是我的 TARGET_FILE 不会保存?

有人可以帮忙吗?我已经用 '

Imports System.IO
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    'Get folder containing files to ellipherate through...
    Dim TARGET_FILE() As String = IO.Directory.GetFiles("C:\VTS\TREADSTONE LT\ATC", "*", SearchOption.AllDirectories)

    For Each file As String In TARGET_FILE

        Dim sReader As New StreamReader(file)
        Dim content As String = sReader.ReadToEnd()
        sReader.Close()

        If Text.Contains("Index...") Then
            'do nothing
        Else
            Dim text As String = IO.File.ReadAllText(TARGET_FILE) '<<----ISSUE #1
            Dim EXTRA As String = IO.File.ReadAllText("C:\STUFF.TXT")
            Dim index As Integer = text.IndexOf("<Tools>")
            Dim countChars As Integer
            countChars = "<Tools>".Length
            If index >= 0 Then

                ' String is in file, starting at character "<Tools>" insert text "TEST_HELLO"
                text = text.Insert(index + countChars, EXTRA)

                Dim Writer As System.IO.StreamWriter
                Writer = New System.IO.StreamWriter(TARGET_FILE) '<<----ISSUE #2
                Writer.Write(text)
                Writer.Close()

                'Close this program\ form...
                'Me.Close()

            End If
        End If

    Next

    Me.Close()
End Sub

【问题讨论】:

    标签: vb.net getfiles


    【解决方案1】:
    Dim TARGET_FILE() As String 'This represent an array of string
    

    File.ReadAllText

     System.IO.StreamWriter
    

    不接收字符串数组作为参数

    您应该迭代您的 TARGETFILE 数组集合并为每个文件执行 ReadAllText

     For Each File As String In TARGETFILE
             Dim ReadedText as string = System.IO.File.ReadAllText(File)
             Dim writer As New System.IO.StreamWriter("DestinationPath")
             writer.Write(ReadedText )
             Write.Close()
     Next
    

    【讨论】:

    • Err 现在我迷路了,我已经用你的代码替换了我的每个文件,正如它现在所有的混乱所暗示的那样?
    • 您必须使用 foreach 来读取您从目录中获取的 TARGETFILE 集合中的每个文件。在 For each 语句中,您可以执行所需的操作。我刚刚给你发了一个例子
    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多