Search code examples
c#directorystoragestreamwriter

How to always write to an existing local drive using C# StreamWriter


Apologies for the poor title wording,

I have a StreamWriter set up in my C# program that creates and then writes to multiple text files on a local storage drive. The issue is that as I test this program on multiple machines - the names of the drives are inconsistent from machine to machine and do not always have a C: , D: , etc. As a result I experience errors whilst trying to write to drives that do not exist.

I have attempted to not specify the drive to be written to in the hopes that it would default to an existing drive as the specific location is unimportant for my needs. I.e. "C:\\wLocation.txt" becomes "wLocation.txt" but this did not seem to fix anything.

Code:

public static string getWeatherLocation()
    {
        String locationFile = "C:\\wLocation.txt";
        String location;

        try
        {
            System.IO.StreamReader reader = new StreamReader(locationFile);
            location = reader.ReadLine();
            reader.Close();
            return location;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

I'm not particularly knowledgeable with regards to the StreamWriter so the solution may be fairly simple but any help would be appreciated.


Solution

  • You can use System.IO.DriveInfo.GetDrives to get a list of drives on the machine:

    DriveInfo[] allDrives = DriveInfo.GetDrives();
    
    foreach (DriveInfo d in allDrives)
    {
        Console.WriteLine(d.Name); //C:\ etc.
    }
    

    You can then simply compose the file name of the given volume label and your desired file name:

    var filePath = d.Name + "filename.txt";
    

    Or better:

    var filePath = Path.Combine(d.Name, "filename.txt");