How to write in Text file on desktop in

write text file in, write text file in c#, text file in c#, text file in, write data to text file in


Here, in this article showing how to write in Text file on desktop in 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.

Public 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\"

    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
    End If

    Dim fi As FileInfo = New FileInfo(FilePath)
    Dim sw As StreamWriter
    If Not fi.Exists Then
        sw = fi.CreateText()
    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

public 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) {

  FileInfo fi = new FileInfo(FilePath);
  StreamWriter sw = default(StreamWriter);
  if (!fi.Exists) {
   sw = fi.CreateText();
 } catch (Exception ex) {
  MessageBox.Show("Writting to test folder error occurred!" + ex.Message.ToString);
  return false;
 return true;


In this article, I have explained this article with code snippet on How to write in Text file on desktop in Hope it will help to everyone to write in text file on desktop.



Anjan Kant

Outstanding journey in Microsoft Technologies (ASP.Net, C#, SQL Programming, WPF, Silverlight, WCF etc.), client side technologies AngularJS, KnockoutJS, Javascript, Ajax Calls, Json and Hybrid apps etc. I love to devote free time in writing, blogging, social networking and adventurous life

Post A Comment: