Unable to write to a file in Azure App Service

Sarthak Kathuria 6 Reputation points Microsoft Employee
2021-10-18T08:13:09.457+00:00

Situation:

I have been trying to download some files from the Azure Dev Ops repository using GIT API. I then store these files in a new folder with folder name as Office-{MergeCommitID}. Then process these files. And then, delete the temporary folder. In order to download the files I have to get the content of the files and write them to a file in the temporary folder. The code that I use to write to file is:

private void WriteToFile(string fileName, string content, string directoryPath)
        {
            int noOfRetries = 3;
            string filePath = Path.Combine(directoryPath, fileName);
            String processedDirectoryPath = Path.GetDirectoryName(directoryPath);
            for (int i = 1; i <= noOfRetries; i++)
            {
                try
                {
                    if (!Directory.Exists(processedDirectoryPath))
                    {
                        Directory.CreateDirectory(processedDirectoryPath);
                    }

                    if (Directory.Exists(processedDirectoryPath))
                    {

                        ProcessDirectory(processedDirectoryPath);

                        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                        {
                            logger.LogInformation($"WriteToFile trying to write the {content} to file: {filePath}");
                            var bytes = Encoding.UTF8.GetBytes(content);
                            fs.Write(bytes);
                        }
                        logger.LogInformation($"WriteToFile: was successful in writing to the file: {filePath}");
                        break;
                    }
                    else
                    {

                        logger.LogError($"WriteToFile: Directory ({directoryPath})does not exist!");
                        throw new DirectoryNotFoundException();
                    }
                }
                catch(Exception ex)
                {
                    if(i == 1)
                    {
                        logger.LogWarning($"An exception: {ex} occured while writing to the file: {filePath}");
                    }
                    else if(i == noOfRetries)
                    {
                        string errorMessage = $"WriteToFile method failed due to the following exception: {ex} while writing on the file: {filePath}";
                        logger.LogError(errorMessage);
                        throw ex;
                    }
                }
            }

I have added the ProcessDirectory method to check if it was possible or not to access the directory as it the application was earlier failing on the line where I create the FileStream object. The ProcessDirectory function looks like this:

 public void ProcessDirectory(string targetDirectory)
        {
            // Process the list of files found in the directory.
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
                ProcessFile(fileName);

            // Recurse into subdirectories of this directory.
            string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
                ProcessDirectory(subdirectory);
        }

        // Insert logic for processing found files here.
        public void ProcessFile(string path)
        {
            logger.LogInformation("Processed file '{0}'.", path);
        }

I am getting the following exception when I try the above process:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\home\site\wwwroot\Office-12aae1d40b045f5612b175742a7c720452143ca2'.
   at SecurityCodeScannerTask.DataProcessor.GitDataProcessor.WriteToFile(String fileName, String content, String directoryPath) in C:\Users\sakathuria\source\repos\OESecTools\SecurityCodeScanner\SecurityCodeScannerTask\DataProcessor\GitDataProcessor.cs:line 655
   at SecurityCodeScannerTask.DataProcessor.GitDataProcessor.DownloadFilesPerCommit(List`1 changedFiles, GitData gitData) in C:\Users\sakathuria\source\repos\OESecTools\SecurityCodeScanner\SecurityCodeScannerTask\DataProcessor\GitDataProcessor.cs:line 461

I got the following error in the logs that I have added:

WriteToFile method failed due to the following exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\home\site\wwwroot\Office-12aae1d40b045f5612b175742a7c720452143ca2'.
   at System.IO.Enumeration.FileSystemEnumerator`1.CreateDirectoryHandle(String path, Boolean ignoreNotFound)
   at System.IO.Enumeration.FileSystemEnumerator`1.Init()
   at System.IO.Enumeration.FileSystemEnumerator`1..ctor(String directory, Boolean isNormalized, EnumerationOptions options)
   at System.IO.Enumeration.FileSystemEnumerable`1..ctor(String directory, FindTransform transform, EnumerationOptions options, Boolean isNormalized)
   at System.IO.Enumeration.FileSystemEnumerableFactory.UserFiles(String directory, String expression, EnumerationOptions options)
   at System.IO.Directory.InternalEnumeratePaths(String path, String searchPattern, SearchTarget searchTarget, EnumerationOptions options)
   at System.IO.Directory.GetFiles(String path)
   at SecurityCodeScannerTask.DataProcessor.GitDataProcessor.ProcessDirectory(String targetDirectory) in C:\Users\sakathuria\source\repos\OESecTools\SecurityCodeScanner\SecurityCodeScannerTask\DataProcessor\GitDataProcessor.cs:line 584
   at SecurityCodeScannerTask.DataProcessor.GitDataProcessor.WriteToFile(String fileName, String content, String directoryPath) in C:\Users\sakathuria\source\repos\OESecTools\SecurityCodeScanner\SecurityCodeScannerTask\DataProcessor\GitDataProcessor.cs:line 626 while writing on the file: D:\home\site\wwwroot\Office-12aae1d40b045f5612b175742a7c720452143ca2\-cloudbuildtools-tools-NuTest.UnitTests-packages.lock.json

One reason that can be possible is that I am using Azure Dev Ops pipeline for deploying the code on AppService and it uses ZipDeploy.

Unable to Create Directories due to ZipDeploy

I tried to publish the code using Visual Studio on AppService but it gave me the same error again. Any help in resolving this issue is much appreciated.

Office Management
Office Management
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Management: The act or process of organizing, handling, directing or controlling something.
2,010 questions
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
36,147 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Monalla-MSFT 11,646 Reputation points
    2021-10-18T16:24:09.707+00:00

    Hello @Sarthak Kathuria - Thanks for reaching out.

    Devops is not currently supported here on Microsoft QnA. The Community Members and Engineers are actively answering questions in dedicated forums here. Please post your question in that forum :
    https://developercommunity.visualstudio.com/spaces/21/index.html

    https://azure.microsoft.com/en-in/support/devops/

    Please don't forget to Accept as answer if the reply is helpful..