C
C#2y ago
Solar

❔ Code Not Writing To Text File

So I'm very new to c# (Just Started A couple hours ago) I code other languages though so I'm not a complete beginner but basically all I need help with is diagnosing and fixing why my method wont write to a text file

public static void Writer(string paintingType, int saleVal)
{
if (File.Exists("paintingHistory.txt"))
{

}
else
{
File.Create("paintingHistory.txt");
}
int cost = paint_Types[paintingType];
string data = paintingType+":" +":"+ Convert.ToString(cost)+":" + Convert.ToString(saleVal)+":\n";

using (StreamWriter sw = File.AppendText("paintingHistory.txt"))
{
sw.WriteLine(data);
}
return;


}

public static void Writer(string paintingType, int saleVal)
{
if (File.Exists("paintingHistory.txt"))
{

}
else
{
File.Create("paintingHistory.txt");
}
int cost = paint_Types[paintingType];
string data = paintingType+":" +":"+ Convert.ToString(cost)+":" + Convert.ToString(saleVal)+":\n";

using (StreamWriter sw = File.AppendText("paintingHistory.txt"))
{
sw.WriteLine(data);
}
return;


}
169 Replies
tacosontitan
tacosontitan2y ago
Since you're just starting with C# and simply writing text to a file, I recommend using the simpler File.WriteAllText method.
tacosontitan
tacosontitan2y ago
File.WriteAllText Method (System.IO)
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
Solar
SolarOP2y ago
Its multiple inputs over an infinite span of time
Mango
Mango2y ago
Look up StreamWriter or any of the File.WriteAll…. Methods
Solar
SolarOP2y ago
its a data tracker so as data is inputted it needs to append it to a new line
Dropps
Dropps2y ago
whats the true problem you trying to achieve then?
Solar
SolarOP2y ago
I did it in python ill send that code so maybe u can kinda understand'
Dropps
Dropps2y ago
whenever you get nrw input just take out all text string append and put back imo
Mango
Mango2y ago
File.AppendText(String) Method (System.IO)
Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.
Solar
SolarOP2y ago
def writer(type,price,sold):
print(type,price,sold)
text = "{}:{}:{}:\n".format(type,price,sold)
print(text)
with open("paintingHistory.txt","a") as f:
f.write(text)
f.close()
def writer(type,price,sold):
print(type,price,sold)
text = "{}:{}:{}:\n".format(type,price,sold)
print(text)
with open("paintingHistory.txt","a") as f:
f.write(text)
f.close()
Mango
Mango2y ago
God no
Solar
SolarOP2y ago
yea no that seems inefficent as all hell
Mango
Mango2y ago
See my link above
tacosontitan
tacosontitan2y ago
string existingData = File.ReadAllText("C:\\paintingHistory.txt");
int cost = paint_Types[paintingType];
string data = paintingType+":" +":"+ Convert.ToString(cost)+":" + Convert.ToString(saleVal)+":\n";
string newData = existingData + data;
File.WriteAllText("C:\\paintingHistory.txt", newData);
string existingData = File.ReadAllText("C:\\paintingHistory.txt");
int cost = paint_Types[paintingType];
string data = paintingType+":" +":"+ Convert.ToString(cost)+":" + Convert.ToString(saleVal)+":\n";
string newData = existingData + data;
File.WriteAllText("C:\\paintingHistory.txt", newData);
Why can't you do something like that? Solve performance problems when they arise, not ahead of time
Solar
SolarOP2y ago
think about how many lines could come and how inefficent that would end up being
Mango
Mango2y ago
He doesn’t need to do that though
tacosontitan
tacosontitan2y ago
Is this for practice or a production level application?
Dropps
Dropps2y ago
idk if you truly need a txt file for it a db sounds more appropriate here
tacosontitan
tacosontitan2y ago
My understanding was that this was for learning
Solar
SolarOP2y ago
practice but I like to get dropped into the deep end
Dropps
Dropps2y ago
you have table data
tacosontitan
tacosontitan2y ago
This TBH
Solar
SolarOP2y ago
how do you make a db
Dropps
Dropps2y ago
ef core or dapper most commonly ef core
Mango
Mango2y ago
It’s more steps
tacosontitan
tacosontitan2y ago
Well that's how to interact with it
Mango
Mango2y ago
But do you want to make a text file just as a basic log?
tacosontitan
tacosontitan2y ago
Depends on which provider you want to go with
Solar
SolarOP2y ago
no no db is good I would like to learn that too any resources for that?
tacosontitan
tacosontitan2y ago
SQL server is pretty common in the .NET world
Dropps
Dropps2y ago
just search "ef core"
Mango
Mango2y ago
Then use Microsoft.Data.SqlClient
Dropps
Dropps2y ago
and you get a whole load of resources sqlite for anything smaller
tacosontitan
tacosontitan2y ago
MongoDB kekw
Mango
Mango2y ago
Learners should not skip the foundations as to why we got to EF Core
Dropps
Dropps2y ago
eww
Mango
Mango2y ago
Vomit
Dropps
Dropps2y ago
i never wrote a single line of sql myself
tacosontitan
tacosontitan2y ago
You should 🙂
Mango
Mango2y ago
Congrats. You would be expected to as a full-stack where I am.
tacosontitan
tacosontitan2y ago
Not saying every day But good knowledge to have at least
Dropps
Dropps2y ago
iam a full stack as well
tacosontitan
tacosontitan2y ago
Especially for someone learning Not if you've never written any SQL
Mango
Mango2y ago
Congrats. I write SQL when I have to, which is rare but I know how to
Dropps
Dropps2y ago
i do as well know how to as i can read it but i never needed to write it
Mango
Mango2y ago
That is rare and really not common
tacosontitan
tacosontitan2y ago
I have to use Dapper because my boss won't let us use EF 😭
Mango
Mango2y ago
Unless other people are doing it for you You have my pity
tacosontitan
tacosontitan2y ago
So I still have deal with it by hand kekw okay That's been most of my career
Dropps
Dropps2y ago
clone ef by hand
Mango
Mango2y ago
I get to maintain EF Core and sprocs For SSRS
tacosontitan
tacosontitan2y ago
My early career exposed me to the likes of SqlBulkCopy 😄
Mango
Mango2y ago
Can’t use ORMs for SSRS
Dropps
Dropps2y ago
maybe we should go back to #chat
tacosontitan
tacosontitan2y ago
Don't disagree @Solar, did we answer your questions? I know we derailed a bit
Dropps
Dropps2y ago
"a bit" yes
Solar
SolarOP2y ago
Im currently trying to figure out efcore
Dropps
Dropps2y ago
if any questions further just ping us
tacosontitan
tacosontitan2y ago
Best of luck tacowave
Solar
SolarOP2y ago
Honestly its just an application for sims lol my girlfriend plays so I wanted to make her a thing that keeps track of paintings and her net gain etc
Mango
Mango2y ago
Yeah, my teaching style is “Heres the best method to do this, but here’s why we do it this way”
Dropps
Dropps2y ago
you forgot the "p" there
Solar
SolarOP2y ago
huh wait do i need to buy something in order for efcore to work properly like do i need to have a server
Mango
Mango2y ago
You know MS still recommends reviewing migration code. The classes and such With EF Core
Solar
SolarOP2y ago
i am reading it now
Mango
Mango2y ago
You need SQL Server Developer edition which is free I would say get 2022
Dropps
Dropps2y ago
ef core is just a mapper between your classes and a SQL server or whatever data source you have you maybe want an sql server (simply spin up using docker) or use a sql lite single file based db
Mango
Mango2y ago
Or MySQL Community 8 Gross Both are free
Solar
SolarOP2y ago
Idk which one to get lmao i got this one
No description
Solar
SolarOP2y ago
is that right'
Mango
Mango2y ago
That’s right. I would go with Basic since you’ve never setup SQL server before
Solar
SolarOP2y ago
woah woah woah bold of you to assume
Mango
Mango2y ago
Or if you want to follow a tutorial and do custom
Solar
SolarOP2y ago
I haven't but still bold of you to assume lmao
Dropps
Dropps2y ago
basic = install here with defaults custom = set some settings prior to install download = download the installer to install it on a server that doesnt have internet access
Mango
Mango2y ago
I don’t have to since you asked “Do I have to have a server?” When we said to get a KekwRGB
Solar
SolarOP2y ago
lol wait can i upload movies to an sql server
Mango
Mango2y ago
As a blob? Sure
Dropps
Dropps2y ago
yes
Solar
SolarOP2y ago
so basically I could make walmart brand plex
Dropps
Dropps2y ago
sql server is more of a dump in me anything storage my autocorrect on phone almost made this nsfw whoops
Mango
Mango2y ago
Anything except for all my regrets I mean Wat
Solar
SolarOP2y ago
i read the download wrong and it looked like it said 1.1 mil mb download
Mango
Mango2y ago
Can’t remember if there’s a screen for basic install or not that asks you what kind of authentication you want to use I’ve always done Custom But I would recommend going with Mixed Mode Authentication
Solar
SolarOP2y ago
so Ill do the server later but for now what would be the best way for text file
Mango
Mango2y ago
The link I posted last
Solar
SolarOP2y ago
its just i have mcdonalds wifi
Mango
Mango2y ago
File.AppendText If all you need to do is add to the next line And not view the contents after
Solar
SolarOP2y ago
so looking at ur link ive done what it says and it still wont work
Dropps
Dropps2y ago
i still recommend running it as a docker container more cause a dev db you dont need to constantly eat up resources
Mango
Mango2y ago
That can come later Let him figure out this first Docker has nothing to do with the requirements of what he’s trying to learn
Dropps
Dropps2y ago
just for the dev db there as a suggestion plus as he isnt a total dev newbie he might already know docker
Solar
SolarOP2y ago
oh its the path
Mango
Mango2y ago
I think at least the directory path has to exist. If the file doesn’t it will make it
Dropps
Dropps2y ago
depends on the dotnet version as far as i remember
Mango
Mango2y ago
Yeh he needs to read that documentation That’s for latest
Dropps
Dropps2y ago
yep
Solar
SolarOP2y ago
so how do i make a path that means its in the same folder as the file of text
Mango
Mango2y ago
Look up Path.Combine()
Dropps
Dropps2y ago
var path = Path.Combine(your, path, parts) if (Path.Exists(path) { blah }
Mango
Mango2y ago
File, Path, Directory are all classes you would likely use here
Dropps
Dropps2y ago
filestream as well maybe
Mango
Mango2y ago
Definitely File and Path
Solar
SolarOP2y ago
no no i mean if i put it on another pc i want it to work but the path wont be the same so how do i make it figure out the path that its in
Mango
Mango2y ago
Ah that probables Problem Relative paths
Solar
SolarOP2y ago
yessir I used to know how to do em but i forgot em lol
Dropps
Dropps2y ago
you always think of the base as where your .exe is located (or whatever you compile to) and from there you go up 1 folder with ./../
Mango
Mango2y ago
I usually do var path = Path.Combine(AppDomain.Current.BaseDirectory, "path", "to", "my", "file.txt");
Dropps
Dropps2y ago
and down with well its name
Solar
SolarOP2y ago
but what if they put it on the desktop and i put it in my photos
Mango
Mango2y ago
Where do you want it to go?
Solar
SolarOP2y ago
uh so id want the exe to go on desktop and the file to go in program files i guess
Dropps
Dropps2y ago
FileSystem.SpecialDirectories.Desktop exists i think unless that was a maui specific thing
Mango
Mango2y ago
Yeah see if C#/.NET has a way to get you an absolute path to Desktop the thing is it is user based so the path will have their windows user name in it
Solar
SolarOP2y ago
idc abt user based just computer based for now
Mango
Mango2y ago
Im telling you Windows Desktop path is user specific as in current user
Solar
SolarOP2y ago
oh
Dropps
Dropps2y ago
nope there is both there is user based and a generic for all
Solar
SolarOP2y ago
can I just make it a relative path to the folder and it loads from where ever the folder is put or does it have to be full path
Mango
Mango2y ago
The public profile?
Dropps
Dropps2y ago
yes
Mango
Mango2y ago
well yeah, thats still a user in the users directoryt sorta
Solar
SolarOP2y ago
if i did something like /ProjectFolder/Textfile.txt/ would that be enough
Dropps
Dropps2y ago
everything inside the public profile is always on every user as well you need to be an admin to remove it from there tho
Mango
Mango2y ago
One thing I hate about Windows 11 They dont want you setting up a local user You can put the file anywhere
Dropps
Dropps2y ago
just setup using for company
Mango
Mango2y ago
put it in System32 i dare you
Dropps
Dropps2y ago
then it lets you
Solar
SolarOP2y ago
na
Dropps
Dropps2y ago
i put my data always on C:\<companyname>\<appname>\data
Mango
Mango2y ago
I have 4 letterd drives, 2 of which are RAID1? RAID0? i dont remember 8 TB for games under 1 letter mmmmmmmmmmmmmmmmmmmmmmmmmmm
Solar
SolarOP2y ago
so i did what i said and it says could not find part of path but then literally shows the entire path
Mango
Mango2y ago
enter debug mode, put a breakpoint where you are making the path, read it, open up explorer and manually see if you can go ther if not theres your problem
Solar
SolarOP2y ago
it says excepetion unhandled
Mango
Mango2y ago
if you can, see @Hazel | へいぜる
Solar
SolarOP2y ago
I just manually typed the path string path = "HelloWorld/HelloWorld/paintingHistory.txt";
Mango
Mango2y ago
thats not going to work
Solar
SolarOP2y ago
it should 😦
Mango
Mango2y ago
File.AppendText needs an absolute path what you gave it is not im assuming this is a console app type project?
Solar
SolarOP2y ago
yes
Mango
Mango2y ago
and you want the file to be saved in the same directory that it is in?
Solar
SolarOP2y ago
yes
Mango
Mango2y ago
then this needs to be your path
Solar
SolarOP2y ago
ok but can you explain why too and why it matters that its a console app
Mango
Mango2y ago
string path = Path.Combine(AppDomain.Current.BaseDirectory, "paintingHistory.txt"); I was just wondering, has nothing to do with what kind of app it is
Solar
SolarOP2y ago
No description
Mango
Mango2y ago
maybe its CurrentDomain use autocomplete to tell you
Solar
SolarOP2y ago
yea it suggested that wanted to make sure tho
Mango
Mango2y ago
autocomplete is pretty much right unless someone messed up
Solar
SolarOP2y ago
that didnt work nothing was entered
Mango
Mango2y ago
you're supposed to be using File.AppendText not File.Create
Solar
SolarOP2y ago
nono thats my checking if it exists the append is lower
Solar
SolarOP2y ago
No description
Solar
SolarOP2y ago
No description
Solar
SolarOP2y ago
come to think of it its not doing the file exists output either whats the c# equiv of sleep
tacosontitan
tacosontitan2y ago
Thread.Sleep
Solar
SolarOP2y ago
thx
tacosontitan
tacosontitan2y ago
Most external operations should be async though, which gives you access to Task.Delay instead Since you like diving off the deep end, I'd look into that at some point too
Solar
SolarOP2y ago
ok so it says file exists so now the only mystery is why its not writing
Mango
Mango2y ago
It's not going to be in the location where the Program.cs is if you ran a Debug build it will be in the bin/Debug/netwhatever location
Solar
SolarOP2y ago
i figured it out yea i think so
Mango
Mango2y ago
No description
Solar
SolarOP2y ago
how do i run in non debug
Mango
Mango2y ago
I'll let you google that im going to take a shower now
Solar
SolarOP2y ago
ok i did it but it still says file exists when i deleted it I have idea I have made it print out the path alr it works now thx guys!
JakenVeina
JakenVeina2y ago
welcome to the party, BTW
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?