View difference between Paste ID: Q4Dhkfn5 and DFDfvq9h
SHOW: | | - or go back to the newest paste.
1-
    'シリアライズ
1+
Public Class Form1
2-
    Private Sub Serialize(ByVal fileName As String, ByVal mySettings As Settings)
2+
3-
        'XMLファイルに保存する
3+
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
4-
        Dim serializer As New Serialization.XmlSerializer(GetType(Settings))
4+
        Debug.WriteLine(ReturnFileName("test.xml", "xml"))
5-
        '書き込むファイルを開く    ファイルモードはCreateで開くこと
5+
        Debug.WriteLine(ReturnFileName("test.XML", ".xml"))
6-
	’OpenOrCreateで開くとシリアル化に失敗する場合としない場合があるので
6+
        Debug.WriteLine(ReturnFileName("test", "xml"))
7-
        Try
7+
        Debug.WriteLine(ReturnFileName("test.xxx", "xml"))
8-
            Using fs As New FileStream(fileName, FileMode.Create)
8+
        Debug.WriteLine("-------------------------------------------------------")
9-
                serializer.Serialize(fs, mySettings)
9+
    End Sub
10-
            End Using
10+
11-
        Catch ex As Exception
11+
12-
            Dim message As String = "設定ファイルの書き込み(シリアル化)に失敗しました"
12+
    ''' <summary>
13-
            message &= vbCrLf & "理由:" & ex.Message
13+
    ''' ユーザーに特定の拡張子(ここではxmlとする)のファイル名を指定して欲しい時に、
14-
            MsgBox(message, MsgBoxStyle.Information)
14+
    ''' ユーザーが
15-
            Exit Sub
15+
    ''' test.xml
16-
        End Try
16+
    ''' test.XML
17-
    End Sub
17+
    ''' test
18
    ''' test.xxx
19
    ''' を指定した場合、ReturnFileNameはそれぞれの場合に以下の文字列を返す。
20
    ''' test.xml → test.xml
21
    ''' test.XML → test.XML
22
    ''' test     → test.xml
23
    ''' test.xxx → test.xxx.xml
24
    ''' 
25
    ''' つまり、
26
    ''' ●拡張子がxmlの場合はそのまま。
27
    ''' ●拡張子がなければ".xml"を追加する。
28
    ''' ●既にxml以外の拡張子が付いている場合は、その後に".xml"を追加する。
29
    ''' </summary>
30
    Private Function ReturnFileName(sFileName As String, ext As String)
31
        Dim index As Integer
32
        Dim tempExt As String
33
34
        'extに"."が付いていない場合は"."を追加する。
35
        If Not ext.Contains(".") Then
36
            ext = "." & ext
37
        End If
38
39
        index = sFileName.LastIndexOf(".")
40
        Select Case index
41
            Case Is = -1 '▼拡張子が付いていない場合
42
                sFileName = sFileName & ext
43
            Case Is > 0 '▼拡張子が付いている場合は拡張子が ext の場合とそうでない場合で処理を分ける。
44
                'sFileNameの拡張子を取得する。
45
                tempExt = sFileName.Substring(index, sFileName.Length - index)
46
                '▼拡張子が ext でない場合
47
                If tempExt.ToLower <> ext.ToLower Then
48
                    sFileName = sFileName & ext
49
                End If
50
        End Select
51
52
        Return sFileName
53
    End Function
54
End Class