Labels

slider

Recent

Navigation

How to write in Text file on desktop in vb.net

write text file in vb.net, write text file in c#, text file in c#, text file in vb.net, write data to text file in asp.net

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.

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

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

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) {
   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;
}

Conclusion

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

Summary

Share

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:

0 comments: