I am trying to create a folder and a text file in a MAUI project. When I run the application, I receive the following message: Base Directory: C:\Users\xyz\AppData\Local Log Directory: C:\Users\xyz\AppData\Local\TestLogs Log File Path: C:\Users\xyz\AppData\Local\TestLogs\testlogfile.txt Test file created successfully. However, the folder TestLogs and file testlogfile.txt are not actually created. How can I resolve this issue?
Here is the content of MauiProgram.cs:
using System;
using System.IO;
using Microsoft.Maui;
using Microsoft.Maui.Hosting;
namespace Hexe
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
// Ermitteln des Pfads zum Stammverzeichnis der Anwendung
string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string logDir = Path.Combine(baseDir, "TestLogs");
string logFilePath = Path.Combine(logDir, "testlogfile.txt");
// Debug-Ausgabe des Pfads
System.Diagnostics.Debug.WriteLine($"Base Directory: {baseDir}");
System.Diagnostics.Debug.WriteLine($"Log Directory: {logDir}");
System.Diagnostics.Debug.WriteLine($"Log File Path: {logFilePath}");
// Erstellen des TestLogs-Ordners, falls nicht vorhanden
try
{
if (!Directory.Exists(logDir))
{
System.Diagnostics.Debug.WriteLine("Creating TestLogs directory...");
Directory.CreateDirectory(logDir);
}
// Test-Datei schreiben
File.WriteAllText(logFilePath, "Dies ist ein Testeintrag, um die Datei- und Ordnererstellung zu überprüfen.");
System.Diagnostics.Debug.WriteLine("Test file created successfully.");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error creating test file: {ex.Message}");
}
return builder.Build();
}
}
}
The development environment is Visual Studio.
You can use File system helpers to create the folder and write the file.
Please check the following code to create the folder and write the file in the app folder:
// Ermitteln des Pfads zum Stammverzeichnis der Anwendung
string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string logDir = Path.Combine(Path.Combine(FileSystem.Current.AppDataDirectory), "TestLogs");
string logFilePath = Path.Combine(logDir, "testlogfile.txt");
Here the log message:
Base Directory: C:\Users\admin\AppData\Local
Log Directory: C:\Users\admin\AppData\Local\Packages\com.companyname.mauiapp2_**\LocalState\TestLogs
Log File Path: C:\Users\admin\AppData\Local\Packages\com.companyname.mauiapp2_**\LocalState\TestLogs\testlogfile.txt