How To Write File Through VB.Net & C#

ms_visual_studio

As I have promised ,today I am going to show you how to create a file, you can write (create) file in different ways same as reading file.

Before you start, have to import System.IO.

[VB.Net]

Imports System.IO

[C#]

using System.IO;

Writing File

Let met to start with the easiest way,

1.WriteAllText

With this function you can create and write file at the same time!

[VB.Net]

File.WriteAllText("c:\CodingTips.txt", "coding is easy !")

[C#]

File.WriteAllText("c:\\CodingTips.txt", "coding is easy !")

2.StreamWriter:

This Pattern is much like reading file.

[VB.Net]

Dim writer As StreamWriter =File.CreateText("c:\CodingTips.txt") 
writer.WriteLine("coding is easy") 
writer.Close()

[C#]

StreamWriter writer = File.CreateText("c:\\CodingTips.txt");
writer.WriteLine("coding is easy");
writer.Close();

3.MemoryStream:

Sometimes you will need to create a stream (the string that you want to write to the file) before you really need to store it somewhere (like in a file). for example you have 5 functions in your code, and each function has a specific result and you want to store the results of these functions in one file, you cannot use the methods that I explained above, in this case, first you need to prepare the stream and then write it to the file, for this purpose MemoryStream would be a good choice,

[VB.Net]

Dim memoryStrm As New MemoryStream()
Dim writer As New StreamWriter(memoryStrm) 

'This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.
writer.WriteLine("Function1") 
writer.WriteLine("Result1")

[C#]

MemoryStream memoryStrm= new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStrm);

//This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.
writer.WriteLine("Function1");
writer.WriteLine("Result1");

After you prepared your MemoryStream you can write it to the file:

[VB.Net]

' Here you must ask the writer to push the data into the 
' underlying stream 
writer.Flush() 
' the create a file stream 
Dim MyFile As FileStream = File.Create("c:\CodingTips.txt") 
' now Write the MemoryStream to the file
memoryStrm .WriteTo(theFile) 
' the you have to Clean up the objects 
writer.Close() 
theFile.Close() 
memoryStrm .Close()

[C#]

// Here you must ask the writer to push the data into the 
// underlying stream 

{
    writer.Flush();
    // the create a file stream 
    FileStream MyFile = File.Create("c:\\CodingTips.txt");
    // now Write the MemoryStream to the file
    memoryStrm.WriteTo(theFile);
    // the you have to Clean up the objects 
    writer.Close();
    theFile.Close();
    memoryStrm.Close();
}

How to get list of the most expensive queries in SQL Server

microsoft_sql_server_icon (1)

SELECT TOP 20
    (total_logical_reads + total_logical_writes) / execution_count AS AverageIO
    ,(total_logical_reads + total_logical_writes) AS TotalIO
    ,qt.text Query
    ,o.name ObjectName
    ,DB_NAME(qt.dbid) AS DATABASEName
FROM 
    sys.dm_exec_query_stats qs
        CROSS APPLY
    sys.dm_exec_sql_text(qs.sql_handle) AS qt
        LEFT OUTER JOIN
    sys.objects o ON o.object_id = qt.objectid          
ORDER BY AverageIO DESC

How to get list of the longest queries in SQL Server

microsoft_sql_server_icon (1)

If you have problem with your database server performance and you do not know where to start your investigation you can use below query to have some clue.

SELECT TOP 20
    qs.total_elapsed_time / qs.execution_count / 1000000.0 AS AverageSecond
    ,qs.total_elapsed_time / 1000000.0 AS TotalSecond
    ,qt.text AS Query
    ,o.name AS OBJECTName
    ,DB_NAME(qt.dbid) DatabaseName
FROM 
    sys.dm_exec_query_stats qs
        CROSS APPLY
    sys.dm_exec_sql_text(qs.sql_handle) AS qt
        LEFT OUTER JOIN 
    sys.objects o ON qt.objectid = o.object_id
ORDER BY AverageSecond DESC

How Read a Files Through VB.Net & C#

Reading and writing files are two of the most common tasks in the world of development. As a .NET developer, .NET Framework makes it easy to perform these tasks.

Before you start, have to import System.IO.

[VB.Net]

Imports System.IO

[C#]

using System.IO;

1.Reading File

There are different ways that you can use them for reading file,

if you want to read a whole file as string, this ways could be fine for you:

[VB.Net]

 Dim Result As String = File.ReadAllText("C:\CodingTips.txt")

[C#]

string Result = File.ReadAllText("C:\\CodingTips.txt");

if you need more properties and futures ,

same as searching specific text in the file, I suppose  this ways is more  efficient:
[VB.Net]

 Private Sub Readfile()
        Dim strReader As StreamReader = File.OpenText("C:\CodingTips.txt")
        ' We will Search the stream until we reach the end or find the specific string.
        While Not strReader.EndOfStream
            Dim line As String = strReader.ReadLine()
            If line.Contains("Code") Then
                'If we find the specific string, we will inform the user and finish the while loop.
                Console.WriteLine("Found Code:")
                Console.WriteLine(line)
                Exit While
            End If
        End While
        ' Here we have to clean the memory.
        strReader.Close()
    End Sub

[C#]

private void Readfile()
{
    StreamReader strReader = File.OpenText("C:\\CodingTips.txt");
    // We will Search the stream until we reach the end or find the specific string.
    while (!strReader.EndOfStream) {
        string line = strReader.ReadLine();
        if (line.Contains("Code")) {
            //If we find the specific string, we will inform the user and finish the while loop.
            Console.WriteLine("Found Code:");
            Console.WriteLine(line);
            break; // TODO: might not be correct. Was : Exit While
        }
    }
    // Here we have to clean the memory.
    strReader.Close();
}

In the next post I will teach you , How to write a file 🙂

Update from in SQL Server (lookup)

sql2008

USE Arm_DB
Go

CREATE TABLE TBL_ARM1
(
ID INT IDENTITY(1,1)
,Title Nvarchar(50)
)

Go

CREATE TABLE TBL_Arm2
(
ID INT Identity(1,1)
,Name Nvarchar(50)
,Arm1_ID Int
,Arm_Title Nvarchar(50)
)


GO 
INSERT INTO TBL_ARM1 VALUES ('Arm1_1')
INSERT INTO TBL_ARM1 VALUES ('Arm1_2')
INSERT INTO TBL_ARM1 VALUES ('Arm1_3')

Go

INSERT INTO TBL_Arm2 (Name ,Arm_Title) VALUES('Mehran','Arm1_1')
INSERT INTO TBL_Arm2 (Name ,Arm_Title) VALUES('Mehran2','Arm1_2')
INSERT INTO TBL_Arm2 (Name ,Arm_Title) VALUES('Mehran3','Arm1_3')



SELECT * FROM TBL_Arm2


UPDATE TBL_Arm2
SET Arm1_ID = A.ID
FROM TBL_ARM1 A
WHERE A.Title = Arm_Title

How can send mail through VB.Net or C# ?

For a developer, e-mail is an effective way to allow an application to send files or reports to users and to notify users of problems or events.Here i am going to explain how can send mail through VB.net or C#.

To send an email you need two objects:

1.MailMessage object: with this object you can create your message that you want to send.

2.SmtpClient object: with this object you can  send your MailMessage to the recipients.

Before you create a function that send mail ,you need to import System.Net.Mail :

[VB.Net]

Imports System.Net.Mail

[C#]

using System.Net.Mail;

Now your code is ready for creating SendMail function

[VB.Net]

 Private Sub SendMail()
        Dim Message As MailMessage = New MailMessage()
        Message.From = New MailAddress("Arman@codingtips.net", "Arman")
        Message.To.Add(New MailAddress("Mehran@codingtips.net", "Mehran"))
        Message.To.Add(New MailAddress("Mike@codingtips.net", "Mike"))
        Message.To.Add(New MailAddress("JM@codingtips.net", "JM"))
        Message.Subject = "Quarterlydata report."
        Message.Body = "See the attached spreadsheet."
        Message.Attachments.Add(New Attachment("C:\Test.txt"))

        Dim sc As SmtpClient = New SmtpClient("smtp.gmail.com")
        sc.Port = 587
        sc.EnableSsl = True
        sc.Credentials = New NetworkCredential("Username", "Password")
        sc.Send(Message)

    End Sub

[C#]

private void SendMail()
{
    MailMessage Message = new MailMessage();
    Message.From = new MailAddress("Arman@codingtips.net", "Arman");
    Message.To.Add(new MailAddress("Mehran@codingtips.net", "Mehran"));
    Message.To.Add(new MailAddress("Mike@codingtips.net", "Mike"));
    Message.To.Add(new MailAddress("JM@codingtips.net", "JM"));
    Message.Subject = "Quarterlydata report.";
    Message.Body = "See the attached spreadsheet.";
    Message.Attachments.Add(new Attachment("C:\\Test.txt"));

    SmtpClient sc = new SmtpClient("smtp.gmail.com");
    sc.Port = 587;
    sc.EnableSsl = true;
    sc.Credentials = new NetworkCredential("Username", "Password");
    sc.Send(Message);

}

Caution:

SmtpClient.port: it depends on the server that you want to use it to send mail.

SmtpClient .Host: it depends on the server that you want to use it to send mail. (here I used “smtp.gmail.com”)

SmtpClient.EnableSsl: If your server is using the SSL you can user this option.

List of all transactions that are running in SQL Server’s instance

microsoft_sql_server_icon (1)

     SELECT sqltext.TEXT
     ,req.session_id
     ,req.status
     ,req.command
     ,req.cpu_time
     ,req.total_elapsed_time
     ,req.blocking_session_id
     ,req.percent_complete
     ,req.estimated_completion_time/1000/60  estimated_completion_time_Min
     ,start_time
    FROM sys.dm_exec_requests req
    CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
    ORDER BY start_time

How to modify and add column in SQL Server’s table with TSQL

sql2008

USE Arm_DB
Go
IF OBJECT_ID('TBL_Persons','U') IS NOT NULL
 DROP TABLE TBL_Persons

CREATE TABLE TBL_Persons
 (
   ID INT IDENTITY PRIMARY KEY
   ,NAME Char(50)
 )

GO

     ALTER TABLE TBL_Persons
     ADD Lname Nvarchar(70)
Go
    ALTER TABLE TBL_Persons
    ALTER COLUMN NAME NVARCHAR(50)
GO
    INSERT INTO TBL_Persons(Name,Lname)
     VALUES ('Arman','Nas')
GO
    SELECT * FROM TBL_Persons

How to save image or any others file type directly from file in SQL Server with binary format

sql2008

USE Arm_DB
GO

IF OBJECT_ID('TBL_Image','U') IS NOT NULL
 DROP TABLE TBL_Image

 CREATE TABLE TBL_Image 
  (
  [ID] INT IDENTITY(1,1)
 ,[Image] VARBINARY(MAX)
   CONSTRAINT PK_TBL_Image PRIMARY KEY CLUSTERED (ID) 
  )
Go
INSERT INTO TBL_Image(Image)
SELECT * FROM OPENROWSET(BULK 'C:\Users\Public\Pictures\Sample Pictures\Koala.JPG',SINGLE_BLOB  ) i

How to create Database in SQL Server with TSQL

sql2008

USE master
GO
CREATE DATABASE Arm_DB 
 ON 
   (
     NAME = Arm_DB_Dat
     ,FILENAME = 'C:\Arman\Mine\MyBlog\Database\Arm_DB_Dat.MDF'
     ,SIZE = 20
     ,MAXSIZE = 200
     ,FILEGROWTH = 8
   ) 
 LOG 
  ON 
    (
     NAME = Arm_DB_Log
     ,FILENAME = 'C:\Arman\Mine\MyBlog\Database\Arm_DB_Log.LDF'
     ,SIZE = 15MB
     ,MAXSIZE = 125MB
     ,FILEGROWTH = 5MB   
    )

GO