LoginSignup
0
0

More than 3 years have passed since last update.

【文字数カウント】指定フォルダ内に存在するテキストファイルを一括で計算

Last updated at Posted at 2020-02-13

業務上、テキストファイルの文字数を計算することが多くありました。

「フォルダ丸ごと文字数カウント」
できるソフトが見つからなかったため、作成しました。

◆言語
VB.Net

◆実行ボタン押下前
mojicount_mae.JPG

◆実行ボタン押下後
mojicount_ato.JPG

◆ソースコード

Imports System.IO
Imports System.Windows.Forms
Imports System.Text

Public Class FrmMain

''' <summary>
''' メイン処理
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub btnExe_Click(sender As Object, e As EventArgs) Handles btnExe.Click

    Try

        '文字数をクリア
        lblTotal.Text = String.Empty

        '入力チェック
        If InputCheck() = False Then
            MessageBox.Show("入力値が正しくありません。")
            Exit Sub
        End If

        '読み込み処理
        ReadProcess()

    Catch ex As Exception
        MessageBox.Show("エラーです。" & vbCrLf & ex.ToString)
    End Try
End Sub

''' <summary>
''' 入力チェック
''' </summary>
''' <returns></returns>
Private Function InputCheck() As Boolean
    If String.IsNullOrEmpty(tbxRead.Text.Trim) OrElse Directory.Exists(tbxRead.Text.Trim) = False Then
        Return False
    End If
    Return True
End Function

''' <summary>
''' 読み込み処理
''' </summary>
Private Sub ReadProcess()

    Dim di As New System.IO.DirectoryInfo(tbxRead.Text)
    Dim files As System.IO.FileInfo() =
        di.GetFiles("*.txt", System.IO.SearchOption.AllDirectories)

    Dim txtPathList As List(Of String) = New List(Of String)
    For Each f As System.IO.FileInfo In files
        txtPathList.Add(f.FullName.ToString)
    Next

    If txtPathList.Count = 0 Then
        MessageBox.Show("テキストファイルが存在しませんでした。")
        Return
    End If

    Dim total As Integer
    For idx As Integer = 0 To txtPathList.Count - 1

        'テキストファイルを開く
        Dim bs As Byte() = System.IO.File.ReadAllBytes(txtPathList(idx))
        Dim sr As New StreamReader(txtPathList(idx).ToString, Encoding.Default)
        Dim str As String = sr.ReadToEnd()
        sr.Close()
        total += str.Length
    Next

    lblTotal.Text = "合計" & total & "文字"

End Sub

''' <summary>
''' フォルダ選択ボタンの押下
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub btnOfd_Click(sender As Object, e As EventArgs) Handles btnFdb.Click

    Dim fbd As New FolderBrowserDialog

    fbd.Description = "フォルダを指定してください。"
    fbd.RootFolder = Environment.SpecialFolder.Desktop
    fbd.SelectedPath = "C:\Windows"
    fbd.ShowNewFolderButton = True

    If fbd.ShowDialog(Me) = DialogResult.OK Then
        tbxRead.Text = fbd.SelectedPath
    End If

End Sub

End Class

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0