C
C#3mo ago
oZion

Can't read from file in same folder

I am trying to select a random line from a txt file in the same folder, it is called "pickupDA.txt" and so I have tried to get the lines from it with File.ReadAllLines("pickupDA.txt"); but it doesnt work. i have tried with "./pickupDA.txt" and "/pickupDA.txt" and ".\pickupDA.txt", none of it works
using MauiAppInformatik.ViewModel;
using System;
using System.IO;

namespace MauiAppInformatik
{
public partial class MainPage : ContentPage
{
private string PLOTD()
{
string[] lines = File.ReadAllLines("pickupDA.txt"); // FIX PATH

int seed = DateTime.Now.DayOfYear;

Random random = new Random(seed);
int randomIndex = random.Next(0, lines.Length);

string selectedLine = lines[randomIndex];

return selectedLine;
}

// More code here
using MauiAppInformatik.ViewModel;
using System;
using System.IO;

namespace MauiAppInformatik
{
public partial class MainPage : ContentPage
{
private string PLOTD()
{
string[] lines = File.ReadAllLines("pickupDA.txt"); // FIX PATH

int seed = DateTime.Now.DayOfYear;

Random random = new Random(seed);
int randomIndex = random.Next(0, lines.Length);

string selectedLine = lines[randomIndex];

return selectedLine;
}

// More code here
No description
4 Replies
canton7
canton73mo ago
That code tries to read from the user's current working directory. By default, that's the folder which contains your application's .exe file, but the user can change that But, if your pickupDA.txt is next to your .cs files, then it won't be next to your .exe
oZion
oZion3mo ago
so i should reference the txt file from the "perspective" of the exe? where is that exe located in maui? google isnt helping
Pobiega
Pobiega3mo ago
If the text file is part of the project, just set up a copy of newer action on the item Can be done in the properties in the solution explorer
OkOk
OkOk3mo ago
I would add a line to print the path of the executable, then run it Like so "Console.WriteLine(System.IO.Path.GetDirectoryName(Application.ExecutablePath));" Then I would change the path to go back as many directories as your text file is in like "../../../pickupDA.txt" Or just put the text file in the same printed path
Want results from more Discord servers?
Add your server
More Posts