C# - How to get file Properties and insert into SQL Server table by using C Sharp

Scenario: Download Script

You are working as C# developer, you need to write a program that can read file's information such as

  •   FolderPath
  •   FileName
  •   LastWriteTime
  •   CreateTime
  •   FileSizeinKB


from a table and write into SQL Server table. Also as part of file information , you would like to insert folder from which we are reading the file properties.


Step 1: 
First of all you need to create a table in SQL Server database in which you would like to insert file information.

CREATE TABLE [dbo].[FileInformation](
id int identity(1,1),
FolderPath VARCHAR(255),
FileName VARCHAR(255),
[LastWriteTime] DateTime,
[CreateTime] Datetime,
FileSizeinKB Int)


Step 2:
Create new Project and then choose Console Application and use below script.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SqlClient;

namespace _01_WriteFileProperitestoTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare Variable and set value,Provide the folder which contains files
            string VarDirectoryPath = "C:\\Source\\";
            //Create Connection to SQL Server
            SqlConnection SQLConnection = new SqlConnection();
            SQLConnection.ConnectionString= "Data Source = (local); Initial Catalog =TechBrothersIT; "
               + "Integrated Security=true;";

            //get all files from directory or folder to get file's information
            string[] files = Directory.GetFiles(VarDirectoryPath);
            SqlCommand SqlCmd = new SqlCommand();
            SqlCmd.Connection = SQLConnection;
            SQLConnection.Open();

            //loop through files
            foreach (string filename in files)
            {

                FileInfo file = new FileInfo(filename);

SqlCmd.CommandText = "Insert into dbo.FileInformation(";
SqlCmd.CommandText += "[FolderPath],[FileName],[LastWriteTime],[CreateTime],[FileSizeinKB])";
SqlCmd.CommandText +=" Values('"
                  + VarDirectoryPath + "','"
                  + file.Name + "','"
                  + file.LastWriteTime + "','"
                 + file.CreationTime 
                 + "','" + file.Length / 1024 
                 + "')";
                 SqlCmd.ExecuteNonQuery();
            }
            SQLConnection.Close();
        }
    }
}

Save the script and then execute. It should read the file properties from the folder you have given and insert into SQL Server Table.
How to read file's properties in C# and insert into SQL Server Table - C# Tutorial


35 comments:

  1. This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it, Affinity at serangoon showroom

    ReplyDelete
  2. I really like your take on the issue. I now have a clear idea on what this matter is all about.. buy instagram likes uk instant

    ReplyDelete
  3. i really like this article please keep it up. gouna villas

    ReplyDelete
  4. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing gouna villas

    ReplyDelete
  5. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. offplan projects for sale in Dubai

    ReplyDelete
  6. With land being an unstable industry, you should invest in a great deal of energy to know the suitable planning and market rates prior to selling your property. Homes for sale in Huntington Hills

    ReplyDelete
  7. Next we tackle the property the board costs. Sell property Ireland

    ReplyDelete
  8. Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!THANKS!!!!!! Sobha windsor whitefield

    ReplyDelete
  9. I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.Guess Bags for Women

    ReplyDelete
  10. I visit your blog regularly and recommend it to all of those who wanted to enhance their knowledge with ease. The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers! Semi Detached duplex for sale in Ibadan Nigeria

    ReplyDelete
  11. I read that Post and got it fine and informative. Plots

    ReplyDelete
  12. Where B14 is the cell straightforwardly to one side of the year in which we are at present ascertaining the property estimation and $B$7 is an outright reference to our "Yearly Appreciation" suspicion. Emergency Tree Service Stockton

    ReplyDelete
  13. We would now be able to compute the measure of our first home loan in the sum segment with the accompanying equation: nova city housing society islamabad payment plan

    ReplyDelete
  14. They should have the entirety of the hardware important to take these, at some point, 100 foot eco frameworks down. Emergency Tree Removal Irvine

    ReplyDelete
  15. Another circumstance is the ice creator. American houses have an ice creator and each time you supplant it, it costs $130 in addition to another $150 for the assistance call. That is nearly $300. Ice producers will keep going for two years.
    plot for sale in university town islamabad

    ReplyDelete
  16. In our venture property model, we should utilize four tabs: property, financing, costs and financials. Tajarat strives to be Pakistan's biggest real estate developer ever, guaranteeing the highest international standards, prompt execution, and lifetime customer loyalty. For further detail visit
    university town plot for sale

    ReplyDelete
  17. Great blog. Really looking forward to read more. Cool.
    Safe Tree Cutting Austin

    ReplyDelete
  18. The following are a few different ways that you can market and sell your house secretly.circa los angeles

    ReplyDelete
  19. Tajarat strives to be Pakistan's biggest real estate developer ever, guaranteeing the highest international standards, prompt execution, and lifetime customer loyalty. For further detail visit lahore smart city location

    ReplyDelete
  20. Inside the property land title there can be various easements, encumbrances, and other enlisted interests which need completely exploring. These interests can affect the value that the property accomplishes at the hour of offer and can likewise effect of the technique for rent inhabitance. properties on sale

    ReplyDelete
  21. These numbers ought to be entered beneath our suspicions box with the primary year beginning in essentially section B. We will complete these qualities to year ten. Projections made past ten years don't have a lot of believability so most monetary models don't surpass ten years. chicago home photos

    ReplyDelete
  22. Really informative article post. Really thank you! Really Great.Woodburn tree removal company

    ReplyDelete
  23. No doubt this is an excellent post I got a lot of knowledge after reading good luck. Theme of blog is excellent there is almost everything to read, Brilliant post. New lenox IL Real Estate Agents

    ReplyDelete
  24. I felt very happy while reading this site. This was really very informative site for me. I really liked it. This was really a cordial post. Thanks a lot!mykonos villas for sale

    ReplyDelete
  25. The whole my assignment help review is amazing, i mean the quality of its service is like off the charts actually and i need to know where i can get me some more of their other features too !! offer home

    ReplyDelete
  26. The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers!Home Maintenance Inspection

    ReplyDelete
  27. I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe reality. this is very nice one and gives in-depth information. thanks for this nice article.Sell My House Fast

    ReplyDelete
  28. I'm so delighted to locate the very same subject I have actually been seeking. Everybody is providing me a great deal of praises today. You're outstanding. As an author, you're so great since you're such an excellent author.Ready Mix Terdekat Jakarta

    ReplyDelete
  29. Every one of these suppositions addresses some part of the continuous expenses of dealing with a property.
    cash buyers Philadelphia

    ReplyDelete
  30. In any case, on the off chance that the year isn't the year we're wanting to sell the property, then, at that point, there is no deal and the deal cost is zero.
    https://www.districtrealty.com/

    ReplyDelete
  31. We should begin with the property tab by renaming the tab "Property" and adding this title in cell A1 of the worksheet. https://www.osgoodeproperties.com/

    ReplyDelete
  32. "Investing in real estate requires careful research and analysis to identify promising opportunities." http://spencerp.net/

    ReplyDelete
  33. I also position a sign in the front yard immediately after purchasing any house. I have purchased several homes in the same regions as a result of marketing this way. Form Follows Efficiency

    ReplyDelete
  34. "One of the advantages of investing in real estate is the ability to leverage your money. By using a mortgage, you can control a larger asset and potentially earn a higher return on your investment." estate planning chandler

    ReplyDelete