【问题标题】:VB.NET Speed up cycle functionVB.NET加速循环功能
【发布时间】:2012-11-23 20:04:45
【问题描述】:

我有这个函数可以在 bin 文件中写入字节。

    Public Shared Function writeFS(path As String, count As Integer) As Integer
        Using writer As New BinaryWriter(File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Write), Encoding.ASCII)
            Dim x As Integer
            Do Until x = count
                writer.BaseStream.Seek(0, SeekOrigin.End)
                writer.Write(CByte(&HFF))
                x += 1
            Loop
        End Using
        Return -1
    End Function

我有一个 count 值的文本框。 Count 是要写入文件的字节数。

问题是当我想写 1mb+ 时,由于循环需要 10+ 秒。

我需要一种更好/更快的方法来在文件 'value' 次的末尾写入十六进制值 FF

如果我没有很好地解释,我很抱歉。

【问题讨论】:

  • 你为什么要这么做writer.BaseStream.Seek(0, SeekOrigin.End)
  • 您是追加到现有文件还是创建新文件?请注意,在每个Write 之后,它已经在文件的末尾。
  • 我正在追加一个现有文件。

标签: vb.net cycle


【解决方案1】:

这样应该更好:

Public Shared Function writeFS(path As String, count As Integer) As Integer
    Using writer As New BinaryWriter(File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Write), Encoding.ASCII)
        Dim x As Integer
        Dim b as Byte
        b = CByte(&HFF)
        writer.BaseStream.Seek(0, SeekOrigin.End)
        Do Until x = count
            writer.Write(b)
            x += 1
        Loop
    End Using
    Return -1
End Function

这样您就不会每次都调用 CByte。并且每次写入后无需移动到流的末尾。

【讨论】:

  • 是的,但在开始写作之前,我需要先到文件末尾,否则会覆盖文件开头的现有数据。写之前只能做一次吗?
  • @DjRikyx 好的,将writer.BaseStream.Seek(0, SeekOrigin.End) 放在循环之前。 (编辑我的答案)
【解决方案2】:

之前的一些问题: 为什么要共享功能?为什么使用 FileSHARE.Write? WriteShare 意味着其他进程可以写入文件,而您写入文件。为什么你写的都是一样的单个字节?为什么函数每次都返回-1?可能更适合使用 SUB?为什么不使用简单的 for 循环来代替 while?

Public Sub writeFS(path As String, count As Integer)
    Using Stream As New FileStream("", FileMode.Append, FileAccess.Write, FileShare.Read)
        Stream.Write(Enumerable.Repeat(Of Byte)(255, count).ToArray, 0, count)
    End Using
End Sub

好的,如果您需要写入 100MB,这不适合,但您可以对写入进行分区。

【讨论】:

  • 它是共享的,因为它是外部类的一部分。我使用文件共享是因为其他程序需要对同一文件具有完全访问权限。此处发布的功能不完整。我只写了我需要帮助的部分。但是,您的问题与问题无关。但是谢谢你的方法,它有效。
猜你喜欢
  • 2016-07-30
  • 2020-10-06
  • 2019-01-29
  • 1970-01-01
  • 2019-05-15
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多