【问题标题】:How to create sub folders when creating file?创建文件时如何创建子文件夹?
【发布时间】:2013-08-23 23:09:17
【问题描述】:

我正在制作一个应用程序,其中涉及读取现有文件的块并将它们写入新文件...现在,问题是我当前使用的代码不会创建子文件夹,然后如果完整路径是文件给定...

如果我给它一个这样的路径:C:\folder1\folder2\file.mp3 它会给出错误,因为文件夹 folder1 和 2 不存在,但是,如果它们不存在,我希望它创建这些子文件夹创建文件时存在...谢谢...这是我的代码:

  Dim bytesRead As Integer
Dim buffer(40096) As Byte

Using inFile As New System.IO.FileStream(arch, IO.FileMode.Open, IO.FileAccess.Read)
    Using outFile As New System.IO.FileStream(path & "\" & f, IO.FileMode.Create, IO.FileAccess.Write)
        inFile.Seek(StartAt, IO.SeekOrigin.Begin)

        Do
            If astop.Text = 1 = False Then
                If CurrentFsize - currtotal < buffer.Length Then
                    ReDim buffer(CurrentFsize - currtotal)
                End If

                bytesRead = inFile.Read(buffer, 0, buffer.Length)
                If bytesRead > 0 Then
                    outFile.Write(buffer, 0, bytesRead)
                    currtotal += bytesRead



                End If
            Else
                Exit Do
                Exit Do

            End If
            Application.DoEvents()

        Loop While bytesRead > 0 AndAlso currtotal < CurrentFsize
    End Using
End Using

【问题讨论】:

  • 我假设您刚刚开始使用以下代码:“If astop.Text = 1 = False Then”是假的。
  • 是的,但是在单击取消时以第二种形式使用 astop,并在循环内检查...
  • astop.Text = 1 = False 实际上是 astop.Text = (1 = False)。 (1 = False) 总是 False。 (1 = False) 可能会被 VB 转换为“False”,但永远不会是“True”
  • if 语句检查 astop.text 是否不为 1,但是,它可以像 if astop.text = then 'do stopping' else ' do copy...
  • 我建议你加括号让逻辑更清楚一点:IF (astop.Text = 1) = False or IF NOT astop.Text =1 Then

标签: vb.net file stream copy


【解决方案1】:

你应该在创建输出文件之前创建path的目录和子目录:

If(Not System.IO.Directory.Exists(path)) Then
    System.IO.Directory.CreateDirectory(path)

【讨论】:

  • 嗯...我想我可以先创建它们,但是,我正在寻找最有效的方法...该程序可能正在处理大量文件,所以即使几毫秒的性能差异确实很重要......
  • 无论如何,您的程序必须创建这些文件夹,无论您使用什么方法。在任何情况下,您的代码都必须在后台调用系统 API 的那些文件夹创建函数。所以你无法用任何其他方法赢得性能。
猜你喜欢
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 2018-12-02
  • 2016-07-19
  • 2021-09-26
  • 1970-01-01
  • 2014-01-17
  • 2015-09-12
相关资源
最近更新 更多