Introduction
Here, in this article showing how to write in Text file on desktop in vb.net. We can use namespace System.Environment.GetFolderPath to get the desktop folder. If particular folder is not created on windows desktop then this code will fully capable to create folder on desktop. if the write to text file already exists then it will delete existed file and then again create a new file and write this text file. Already explained in my previous article Create Folder on Desktop in ASP.NET.12345678910111213141516171819202122232425262728293031Public Function WriteToText(ByVal obj As String, ByVal FileName As String) As Boolean
Dim FilePath As String
FilePath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
FilePath &= "\Sample\Test\"
Try
If Not System.IO.Directory.Exists(FilePath) Then
Dim di As DirectoryInfo = System.IO.Directory.CreateDirectory(FilePath)
End If
FilePath &= FileName
If System.IO.File.Exists(FilePath) = True Then
System.IO.File.Delete(FilePath)
End If
Dim fi As FileInfo = New FileInfo(FilePath)
Dim sw As StreamWriter
If Not fi.Exists Then
sw = fi.CreateText()
sw.Write(obj)
sw.Flush()
sw.Close()
End If
Catch ex As Exception
MessageBox.Show("Writting to test folder error occurred!" + ex.Message.ToString)
Return False
End Try
Return True
End Function
C# Code Snippet
1234567891011121314151617181920212223242526272829303132public bool WriteToText(string obj, string FileName)
{
string FilePath = null;
FilePath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
FilePath += "\\Sample\\Test\\";
try {
if (!System.IO.Directory.Exists(FilePath)) {
DirectoryInfo di = System.IO.Directory.CreateDirectory(FilePath);
}
FilePath += FileName;
if (System.IO.File.Exists(FilePath) == true) {
System.IO.File.Delete(FilePath);
}
FileInfo fi = new FileInfo(FilePath);
StreamWriter sw = default(StreamWriter);
if (!fi.Exists) {
sw = fi.CreateText();
sw.Write(obj);
sw.Flush();
sw.Close();
}
} catch (Exception ex) {
MessageBox.Show("Writting to test folder error occurred!" + ex.Message.ToString);
return false;
}
return true;
}
Post A Comment:
0 comments: