How to Create File On Same Folder For Azure Web Application

Many times we need to create file of folder in web application to store log or other file related information.

The application which is hosted on Azure like Web Jobs or Application has to use different syntax to create file or folder in same or another directory.

Use below code to upload file or folder on Azure Web Application

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

namespace MyFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("File Write Operation Start");

            /*Folder Name Which needs to be Crated on Azure */
            string FolderName = "MyapplicationLogs";

            /*File Name : Here For Demo Purpose to create multiple file I have added FileName in For Loop */
            string FileName;

            //File Content Which needs to be Added in text File
            string strLogText = "Log Information Found on " + DateTime.Now;

            //AZURE Application Root Folder Location + Folder Name Combination 
            //Here  Environment.GetEnvironmentVariable("HOME") gives is Azure Web Application Local Path
            //For e.g. Actial Path for File Creation on Azure will be : D:\home\site\wwwroot\DemoLogs\1Log.txt
            //where D:\home\site\wwwroot is Path for Azure Web Application
            string strFolderName = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot\" + FolderName;

            //If the directory doesn't exist, create it.
            if (!Directory.Exists(strFolderName))
            {
                Directory.CreateDirectory(strFolderName);
            }

            for (int i=0;i<10;i++)
            {
                FileName = i + "Log.txt";

                string strLogFilePath = strFolderName.Trim() + @"\"+ FileName;

                //Once Directory Exists Create or Writre File 
                using (StreamWriter writer = new StreamWriter(strLogFilePath, true))
                {
                    writer.WriteLine(strLogText);
                }

                Console.WriteLine("File Created On Location " + strLogFilePath);
            }
            
            Console.WriteLine("File Write Operation End");
        }
    }
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s