'CSV file not found with C#, Xamarin? (Need guidance)
I am building a BlackJack Game and I want to display the game's stats(e.g. wins, losses, ties, blackjacks, number of games played, highscore) onto the statspage.xaml. But somehow within my statspage's Read method, it has an error that says my file is not found when I had already assigned my csv file to the filePath variable within StatsPage.xaml.cs. I had written down code from Player class to convert the states mention prior:
public static Player Parse(string playerAsString)
{
Player player = null;
string[] fields = playerAsString.Split(',');
int wins = int.Parse(fields[0].Trim());
int losses = int.Parse(fields[1].Trim());
int pushes = int.Parse(fields[2].Trim());
int blackjacks = int.Parse(fields[3].Trim());
int currentscore = int.Parse(fields[4].Trim());
int handsplayed = int.Parse(fields[5].Trim());
int highestscore = int.Parse(fields[6].Trim());
player = new Player();
player.Wins = wins;
player.Losses = losses;
player.Pushes = pushes;
player.Blackjacks = blackjacks;
player.CurrentScore = currentscore;
player.HandsPlayed = handsplayed;
player.HighestScore = highestscore;
return player;
}
And then I created a StatsData class to manage my read and save methods for the stats i want to display (via using CSV file), IDataManager is a superclass of StatsData because it is needed on my Game page as well so that once game page collects the user's stats in also saves the data. In StatsData class:
public class StatsData : IDataManager
{
string _filePath;
public StatsData(string filePath)
{
_filePath = filePath;
}
public void Save (Player players)
{
List<string> playersAsStrings = new List<string>();
foreach (Player player in players)
{
playersAsStrings.Add(player.ToString());
}
File.WriteAllLines(_filePath, playersAsStrings);
}
public Player Read()
{
string[] playersAsString = File.ReadAllLines(_filePath);
Player player = Player.Parse(playersAsString[0]);
return player;
}
}
My GamePage is where i state my csv file with filePath = Path.Combine(FileSystem.AppDataDirectory, "stats.csv"); and also where i call the Read method from StatsData to read data in GamePage. In my statspage.xaml.cs :
public partial class StatsPage : ContentPage
{
IDataManager dataManager;
Player player = new Player();
string _filePath = Path.Combine(FileSystem.AppDataDirectory, "stats.csv");
public StatsPage()
{
InitializeComponent();
dataManager = new StatsData(_filePath);
player = dataManager.Read();
}
private void BackToMainClicked(object sender, EventArgs e)
{
Navigation.PopModalAsync();
}
public string DisplayStats()
{
LblHighScore.Text = $"{player.HighestScore}";
LblHandsPlayed.Text = $"{player.HandsPlayed}";
LblBlackJacks.Text = $"{player.Blackjacks}";
LblWins.Text = $"{player.Wins}";
LblLosses.Text = $"{player.Losses}";
LblPushes.Text = $"{player.Pushes}";
return DisplayStats();
}
The lbl.Text came from the labels in statespage.xaml. Here is the error that I receive: System.IO.FileNotFoundException: 'Could not find file "/data/user/0/com.companyname.blackjack/files/stats.csv"' I apologize for giving to much code but I can't wrap my head around what is wrong.
Solution 1:[1]
In your StatsData class Read() function, I would add a check to see if the file you are attempting to read exists and handle accordingly. Something along the lines of:
public Player Read()
{
if (File.Exists(_filePath)) {
string[] playersAsString = File.ReadAllLines(_filePath);
return Player.Parse(playersAsString[0]);
}
return new Player();
}
So if the file DOES exist, you are going to parse it and provide the values from the file. Otherwise, you're creating a new Player object, which assumes that you have given default values to the properties of the class (Possibly setting all scores, wins, losses, etc. to 0 by default).
I also don't mean this to be condescending, as it has happened to me personally many times before, but please open File Explorer on your PC and navigate to the folder that the file SHOULD be in and validate that it does actually exist at that location.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Travis Lipe |
