I'm getting an error with the optional argument, it says "Constant expression is required"
How I can resolve the problem?
Private Function Write_Text_To_File(ByVal Text_File As String, _
ByVal Text As String, _
ByVal Append_Text As Boolean, _
Optional Encoding As System.Text.Encoding = System.Text.Encoding.Default) As Boolean
Try : Using TextFile As New IO.StreamWriter(Text_File, Append_Text, Encoding) : TextFile.WriteLine(Text) : End Using
Return True
Catch ex As Exception
'Return False
Throw New Exception(ex.Message)
End Try
End Function
UPDATE:
Solution
#Region " Write Text to File "
' [ Write Text to File Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' Write_Text_To_File("C:\Test.txt", "Text", False)
' Write_Text_To_File("C:\Test.txt", "Text", True, System.Text.Encoding.UTF8)
Private Function Write_Text_To_File(ByVal Text_File As String, _
ByVal Text As String, _
ByVal Append_Text As Boolean, _
Optional Encoding As System.Text.Encoding = Nothing) As Boolean
Try
If Encoding Is Nothing Then Encoding = System.Text.Encoding.Default
Using TextFile As New IO.StreamWriter(Text_File, Append_Text, Encoding) : TextFile.WriteLine(Text) : End Using
Return True
Catch ex As Exception
'Return False
Throw New Exception(ex.Message)
End Try
End Function
#End Region
How I can resolve the problem?
Well, you simply can't using Encoding.Default
as a default parameter value.
What you could do is use Nothing
as a default parameter value, and simply have:
If Encoding Is Nothing Then
Encoding = System.Text.Encoding.Default
End If
This does mean you can't use Nothing
for a different meaning, mind you.
Another alternative would be to just use overloading - provide one version without the encoding parameter which just called the version with the encoding parameter, passing in Encoding.Default
.
Two other points to note:
Encoding.Default
is generally a bad default to use (and poorly named). Pretty much everything in .NET actually uses Encoding.UTF8
as the default encoding if you don't specify one; I'd urge you to follow suit.