Module1.vb内に、次のような処理をしてくれるPublic Functionを作りたいです。
つきましては、コードをご教示ください。
0. Public Functionの名前はAaaとする
1. 各種パラメータを受け取る
1-1. strDirPath As String
1-2. strFileName
1-3. strWrite as String
2. もし、strDirPathに格納されているフォルダのパスの中に、strFileNameに格納されている文字列と同じファイル名が存在しなければ、当該ファイル(テキスト)を生成する。
3. 当該ファイルに、strWriteに格納されている文字列を上書きする。
質問の内容だけであれば下記のコードで実現可能です。
Public Sub Aaa(ByVal strDirPath As String, ByVal strFileName As String, ByVal strWrite As String) Using sw As New System.IO.StreamWriter(strDirPath & strFileName, False) sw.Write(strWrite) End Using End Sub
注記
1.Function と指定されていましたが、戻り値の指定が無かったため Sub としています。
2.strDirPath に指定されたフォルダのパスが存在するかのチェックは行っていません。
そのため、存在しないパスが指定されると例外が発生します。
回避するならば以下のようにします。
Public Sub Aaa(ByVal strDirPath As String, ByVal strFileName As String, ByVal strWrite As String) Try Using sw As New StreamWriter(strDirPath & strFileName, False) sw.Write(strWrite) End Using Catch ex As System.IO.DirectoryNotFoundException MessageBox.Show("指定されたフォルダが存在しません") '例としてメッセージボックスの表示 End Try End Sub
ありがとうございます!