C
C#โ€ข8mo 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
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Since you're just starting with C# and simply writing text to a file, I recommend using the simpler File.WriteAllText method.
Hazel ๐ŸŒŠ๐Ÿ’ƒ
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
Solarโ€ข8mo ago
Its multiple inputs over an infinite span of time
Mango
Mangoโ€ข8mo ago
Look up StreamWriter or any of the File.WriteAllโ€ฆ. Methods
Solar
Solarโ€ข8mo ago
its a data tracker so as data is inputted it needs to append it to a new line
Dropps
Droppsโ€ข8mo ago
whats the true problem you trying to achieve then?
Solar
Solarโ€ข8mo ago
I did it in python ill send that code so maybe u can kinda understand'
Dropps
Droppsโ€ข8mo ago
whenever you get nrw input just take out all text string append and put back imo
Mango
Mangoโ€ข8mo 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
Solarโ€ข8mo 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
Mangoโ€ข8mo ago
God no
Solar
Solarโ€ข8mo ago
yea no that seems inefficent as all hell
Mango
Mangoโ€ข8mo ago
See my link above
Hazel ๐ŸŒŠ๐Ÿ’ƒ
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
Solarโ€ข8mo ago
think about how many lines could come and how inefficent that would end up being
Mango
Mangoโ€ข8mo ago
He doesnโ€™t need to do that though
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Is this for practice or a production level application?
Dropps
Droppsโ€ข8mo ago
idk if you truly need a txt file for it a db sounds more appropriate here
Hazel ๐ŸŒŠ๐Ÿ’ƒ
My understanding was that this was for learning
Solar
Solarโ€ข8mo ago
practice but I like to get dropped into the deep end
Dropps
Droppsโ€ข8mo ago
you have table data
Hazel ๐ŸŒŠ๐Ÿ’ƒ
This TBH
Solar
Solarโ€ข8mo ago
how do you make a db
Dropps
Droppsโ€ข8mo ago
ef core or dapper most commonly ef core
Mango
Mangoโ€ข8mo ago
Itโ€™s more steps
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Well that's how to interact with it
Mango
Mangoโ€ข8mo ago
But do you want to make a text file just as a basic log?
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Depends on which provider you want to go with
Solar
Solarโ€ข8mo ago
no no db is good I would like to learn that too any resources for that?
Hazel ๐ŸŒŠ๐Ÿ’ƒ
SQL server is pretty common in the .NET world
Dropps
Droppsโ€ข8mo ago
just search "ef core"
Mango
Mangoโ€ข8mo ago
Then use Microsoft.Data.SqlClient
Dropps
Droppsโ€ข8mo ago
and you get a whole load of resources sqlite for anything smaller
Hazel ๐ŸŒŠ๐Ÿ’ƒ
MongoDB kekw
Mango
Mangoโ€ข8mo ago
Learners should not skip the foundations as to why we got to EF Core
Dropps
Droppsโ€ข8mo ago
eww
Mango
Mangoโ€ข8mo ago
Vomit
Dropps
Droppsโ€ข8mo ago
i never wrote a single line of sql myself
Hazel ๐ŸŒŠ๐Ÿ’ƒ
You should ๐Ÿ™‚
Mango
Mangoโ€ข8mo ago
Congrats. You would be expected to as a full-stack where I am.
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Not saying every day But good knowledge to have at least
Dropps
Droppsโ€ข8mo ago
iam a full stack as well
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Especially for someone learning Not if you've never written any SQL
Mango
Mangoโ€ข8mo ago
Congrats. I write SQL when I have to, which is rare but I know how to
Dropps
Droppsโ€ข8mo ago
i do as well know how to as i can read it but i never needed to write it
Mango
Mangoโ€ข8mo ago
That is rare and really not common
Hazel ๐ŸŒŠ๐Ÿ’ƒ
I have to use Dapper because my boss won't let us use EF ๐Ÿ˜ญ
Mango
Mangoโ€ข8mo ago
Unless other people are doing it for you You have my pity
Hazel ๐ŸŒŠ๐Ÿ’ƒ
So I still have deal with it by hand kekw okay That's been most of my career
Dropps
Droppsโ€ข8mo ago
clone ef by hand
Mango
Mangoโ€ข8mo ago
I get to maintain EF Core and sprocs For SSRS
Hazel ๐ŸŒŠ๐Ÿ’ƒ
My early career exposed me to the likes of SqlBulkCopy ๐Ÿ˜„
Mango
Mangoโ€ข8mo ago
Canโ€™t use ORMs for SSRS
Dropps
Droppsโ€ข8mo ago
maybe we should go back to #chat
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Don't disagree @Solar, did we answer your questions? I know we derailed a bit
Dropps
Droppsโ€ข8mo ago
"a bit" yes
Solar
Solarโ€ข8mo ago
Im currently trying to figure out efcore
Dropps
Droppsโ€ข8mo ago
if any questions further just ping us
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Best of luck tacowave
Solar
Solarโ€ข8mo 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
Mangoโ€ข8mo ago
Yeah, my teaching style is โ€œHeres the best method to do this, but hereโ€™s why we do it this wayโ€
Dropps
Droppsโ€ข8mo ago
you forgot the "p" there
Solar
Solarโ€ข8mo 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
Mangoโ€ข8mo ago
You know MS still recommends reviewing migration code. The classes and such With EF Core
Solar
Solarโ€ข8mo ago
i am reading it now
Mango
Mangoโ€ข8mo ago
You need SQL Server Developer edition which is free I would say get 2022
Dropps
Droppsโ€ข8mo 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
Mangoโ€ข8mo ago
Or MySQL Community 8 Gross Both are free
Solar
Solarโ€ข8mo ago
Idk which one to get lmao i got this one
No description
Solar
Solarโ€ข8mo ago
is that right'
Mango
Mangoโ€ข8mo ago
Thatโ€™s right. I would go with Basic since youโ€™ve never setup SQL server before
Solar
Solarโ€ข8mo ago
woah woah woah bold of you to assume
Mango
Mangoโ€ข8mo ago
Or if you want to follow a tutorial and do custom
Solar
Solarโ€ข8mo ago
I haven't but still bold of you to assume lmao
Dropps
Droppsโ€ข8mo 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
Mangoโ€ข8mo ago
I donโ€™t have to since you asked โ€œDo I have to have a server?โ€ When we said to get a KekwRGB
Solar
Solarโ€ข8mo ago
lol wait can i upload movies to an sql server
Mango
Mangoโ€ข8mo ago
As a blob? Sure
Dropps
Droppsโ€ข8mo ago
yes
Solar
Solarโ€ข8mo ago
so basically I could make walmart brand plex
Dropps
Droppsโ€ข8mo ago
sql server is more of a dump in me anything storage my autocorrect on phone almost made this nsfw whoops
Mango
Mangoโ€ข8mo ago
Anything except for all my regrets I mean Wat
Solar
Solarโ€ข8mo ago
i read the download wrong and it looked like it said 1.1 mil mb download
Mango
Mangoโ€ข8mo 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
Solarโ€ข8mo ago
so Ill do the server later but for now what would be the best way for text file
Mango
Mangoโ€ข8mo ago
The link I posted last
Solar
Solarโ€ข8mo ago
its just i have mcdonalds wifi
Mango
Mangoโ€ข8mo ago
File.AppendText If all you need to do is add to the next line And not view the contents after
Solar
Solarโ€ข8mo ago
so looking at ur link ive done what it says and it still wont work
Dropps
Droppsโ€ข8mo ago
i still recommend running it as a docker container more cause a dev db you dont need to constantly eat up resources
Mango
Mangoโ€ข8mo 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
Droppsโ€ข8mo ago
just for the dev db there as a suggestion plus as he isnt a total dev newbie he might already know docker
Solar
Solarโ€ข8mo ago
oh its the path
Mango
Mangoโ€ข8mo ago
I think at least the directory path has to exist. If the file doesnโ€™t it will make it
Dropps
Droppsโ€ข8mo ago
depends on the dotnet version as far as i remember
Mango
Mangoโ€ข8mo ago
Yeh he needs to read that documentation Thatโ€™s for latest
Dropps
Droppsโ€ข8mo ago
yep
Solar
Solarโ€ข8mo ago
so how do i make a path that means its in the same folder as the file of text
Mango
Mangoโ€ข8mo ago
Look up Path.Combine()
Dropps
Droppsโ€ข8mo ago
var path = Path.Combine(your, path, parts) if (Path.Exists(path) { blah }
Mango
Mangoโ€ข8mo ago
File, Path, Directory are all classes you would likely use here
Dropps
Droppsโ€ข8mo ago
filestream as well maybe
Mango
Mangoโ€ข8mo ago
Definitely File and Path
Solar
Solarโ€ข8mo 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
Mangoโ€ข8mo ago
Ah that probables Problem Relative paths
Solar
Solarโ€ข8mo ago
yessir I used to know how to do em but i forgot em lol
Dropps
Droppsโ€ข8mo 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
Mangoโ€ข8mo ago
I usually do var path = Path.Combine(AppDomain.Current.BaseDirectory, "path", "to", "my", "file.txt");
Dropps
Droppsโ€ข8mo ago
and down with well its name
Solar
Solarโ€ข8mo ago
but what if they put it on the desktop and i put it in my photos
Mango
Mangoโ€ข8mo ago
Where do you want it to go?
Solar
Solarโ€ข8mo ago
uh so id want the exe to go on desktop and the file to go in program files i guess
Dropps
Droppsโ€ข8mo ago
FileSystem.SpecialDirectories.Desktop exists i think unless that was a maui specific thing
Mango
Mangoโ€ข8mo 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
Solarโ€ข8mo ago
idc abt user based just computer based for now
Mango
Mangoโ€ข8mo ago
Im telling you Windows Desktop path is user specific as in current user
Solar
Solarโ€ข8mo ago
oh
Dropps
Droppsโ€ข8mo ago
nope there is both there is user based and a generic for all
Solar
Solarโ€ข8mo 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
Mangoโ€ข8mo ago
The public profile?
Dropps
Droppsโ€ข8mo ago
yes
Mango
Mangoโ€ข8mo ago
well yeah, thats still a user in the users directoryt sorta
Solar
Solarโ€ข8mo ago
if i did something like /ProjectFolder/Textfile.txt/ would that be enough
Dropps
Droppsโ€ข8mo 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
Mangoโ€ข8mo ago
One thing I hate about Windows 11 They dont want you setting up a local user You can put the file anywhere
Dropps
Droppsโ€ข8mo ago
just setup using for company
Mango
Mangoโ€ข8mo ago
put it in System32 i dare you
Dropps
Droppsโ€ข8mo ago
then it lets you
Solar
Solarโ€ข8mo ago
na
Dropps
Droppsโ€ข8mo ago
i put my data always on C:\<companyname>\<appname>\data
Mango
Mangoโ€ข8mo ago
I have 4 letterd drives, 2 of which are RAID1? RAID0? i dont remember 8 TB for games under 1 letter mmmmmmmmmmmmmmmmmmmmmmmmmmm
Solar
Solarโ€ข8mo ago
so i did what i said and it says could not find part of path but then literally shows the entire path
Mango
Mangoโ€ข8mo 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
Solarโ€ข8mo ago
it says excepetion unhandled
Mango
Mangoโ€ข8mo ago
if you can, see @Hazel | ใธใ„ใœใ‚‹
Solar
Solarโ€ข8mo ago
I just manually typed the path string path = "HelloWorld/HelloWorld/paintingHistory.txt";
Mango
Mangoโ€ข8mo ago
thats not going to work
Solar
Solarโ€ข8mo ago
it should ๐Ÿ˜ฆ
Mango
Mangoโ€ข8mo ago
File.AppendText needs an absolute path what you gave it is not im assuming this is a console app type project?
Solar
Solarโ€ข8mo ago
yes
Mango
Mangoโ€ข8mo ago
and you want the file to be saved in the same directory that it is in?
Solar
Solarโ€ข8mo ago
yes
Mango
Mangoโ€ข8mo ago
then this needs to be your path
Solar
Solarโ€ข8mo ago
ok but can you explain why too and why it matters that its a console app
Mango
Mangoโ€ข8mo 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
Solarโ€ข8mo ago
No description
Mango
Mangoโ€ข8mo ago
maybe its CurrentDomain use autocomplete to tell you
Solar
Solarโ€ข8mo ago
yea it suggested that wanted to make sure tho
Mango
Mangoโ€ข8mo ago
autocomplete is pretty much right unless someone messed up
Solar
Solarโ€ข8mo ago
that didnt work nothing was entered
Mango
Mangoโ€ข8mo ago
you're supposed to be using File.AppendText not File.Create
Solar
Solarโ€ข8mo ago
nono thats my checking if it exists the append is lower
Solar
Solarโ€ข8mo ago
No description
Solar
Solarโ€ข8mo ago
No description
Solar
Solarโ€ข8mo ago
come to think of it its not doing the file exists output either whats the c# equiv of sleep
Hazel ๐ŸŒŠ๐Ÿ’ƒ
Thread.Sleep
Solar
Solarโ€ข8mo ago
thx
Hazel ๐ŸŒŠ๐Ÿ’ƒ
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
Solarโ€ข8mo ago
ok so it says file exists so now the only mystery is why its not writing
Mango
Mangoโ€ข8mo 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
Solarโ€ข8mo ago
i figured it out yea i think so
Mango
Mangoโ€ข8mo ago
No description
Solar
Solarโ€ข8mo ago
how do i run in non debug
Mango
Mangoโ€ข8mo ago
I'll let you google that im going to take a shower now
Solar
Solarโ€ข8mo 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
JakenVeinaโ€ข8mo ago
welcome to the party, BTW
Accord
Accordโ€ข8mo 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.
Want results from more Discord servers?
Add your server
More Posts
โœ… input and output file help with 2d arraysHi, using an input file, i must figure out the total rows and colums this 2d array has with the firsโœ… Introduce variable in `while` conditionIs it possible to achieve something like this? (pseudo-C#) ```cs while (Computation() val when val !โœ… How do I specify custom base class for user control?I declared a custom base class derived from `UserControl`. Now in a second assembly, I need to deriโœ… My solution contains absolute paths to projects inside the solution folderI have a solution where all the projects are inside the solution's folder. But VS Community 2022 inโ” Editing the DOM with JS and BlazorHey, I'm building a UI with Blazor Server and I have a question about JS interacting with the DOM inโœ… my code to calculate an average seems to be wrong```using System; using System.Reflection.Metadata; namespace startover { internal class Prograโœ… Message me if you are good at C# I need some help I am beginner I know bit Javascript and a Bit C#Message me if you are good at C# I need some help I am beginner I know bit Javascript and a Bit C#โ” Show error text message under update text box through server validation without refreshingSo basically I want to show an error text message if the user updates and submits an invalid value, โ” Roslyn analyzer rules extractionPls guide me with a solution for extracting a set of rules from any RoslynAnalyzer.dll that it contaโœ… filling byte array with a random intbest approach? ```cs BinaryPrimitives.WriteInt32BigEndian(bytes, Random.Shared.Next(5000000)); //vs