Save all contents in ListBox to .txt file - c#

I am trying to save all contents in a ListBox to a .txt file. I have the following code:
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
SaveFile.WriteLine(listBox1.Items);
SaveFile.ToString();
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
But when I test it the code works but and it acts like it saved the file but when I go into my File Explorer, I cannot see the file anywhere.
Does anyone have any answers

You need to provide the explicit path. Example:
const string sPath = #"C:\MyFolder\save.txt";

What u have to do?
First:
You need a StreamWriter, u done it right. This StreamWriter needs a Path, you did this too.
Second:
You want all Items of your listbox, so use foreach. You havent done this.
Third: Close the Stream, you done it too. Use using instead of close , its better :) do the same :)
Where i find the file? Go to your Project right in Visual Studio right click on it -> open in windows explorer -> bin -> Debug and your text file is their. If you dont give a absolute path, the saved data is always next to your .exe.
Solution:
string path = "save.txt";
using (StreamWriter sw = new StreamWriter(path))
{
foreach (string s in listBox1.Items)
{
sw.WriteLine(s);
}
};

Related

Starting a .exe file but won't work?

I wanted to start a .exe file in a different folder but I wanted other people to also use it and I've been trying many things but it just keeps opening the file that the program that I'm creating is in. (I'm new to c#).
My ex of ^: \Desktop\VSCheatDetector\CheatDetector.exe(the program) and another regular file named viper_screenshare_tool and it has CheatDetector.exe (which I want to open when I click a certain button)
Code:
private void cheat_smasher_click(object sender, EventArgs e)
{
string dir = AppDomain.CurrentDomain.BaseDirectory;
Process.Start(dir, "vipers_screenshare_tool\\CheatDetector.exe");
}
You don't want to use AppDomain.CurrentDomain.BaseDirectory; - I'd suggest using App.config or something like that instead.

Open a .txt file on Android

I am currently working in Unity3D and wish to simply open a .txt file upon clicking on a button.
EDIT : When I say open a .txt file, I mean open it in some editor on the device, not open it asnd save it's content to some string in my app. Kind of like opening a browser to access a website from the app.
Here's the code I currently have (C#) :
private void ShowTextFile(string fileName)
{
Application.OpenURL(Application.streamingAssetsPath + "/PATH/" + fileName);
}
But it's not working ! What am I missing ?
EDIT : I'm expecting for the .txt file to open in another window (like opening a web browser, for example), but it simply isn't doing anything. Not even getting an error.
EDIT2 : I tried using Application.persistentDataPath instead, and in both cases, it says my .txt file doesn't exist. However, when using Application.persistentDataPath, it opens up a message box asking me what I want to open the file with. Whatever I choose, it will give me an error, telling me error loading file or something like that. I've also noticed that it opens "file:///". Is it normal that there is a file:/// before the path ?
EDIT3 (I'm on fire !) : I think the problem might be related to the fact that there is a "." in my path (the com.me.myapp in the data path). Is there any way to avoid this ? Am I even looking at the right path ?
I've tried opening a txt file on Android before, using this:
TextAsset txt = (TextAsset)Resources.Load("file", typeof(TextAsset));
string content = txt.text;
Where file is the name of the txt file (don't need to write file.txt).
The variable string will contain the contents of the text file, you just need to loop through them afterwards.
This method requires:
using System.Text;
using System.IO;
Put file.txt inside a directory named "Resources" (inside Assets dir), if it isn't there then create a new one.
This is my code for Android:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
WWW www = new WWW(rpath);
yield return www;
StringReader streamReader = new StringReader(www.text);
text = streamReader.ReadToEnd();
For iOS:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
StreamReader streamReader = new StreamReader(rpath);
text = streamReader.ReadToEnd();
Note: file_name in StreamingAssets folder
Found a solution that works ! Here's the thing, the streaming assets path, on Android, returns a path that can only be read by a WWW object. So I simply read it with a WWW object then recreated the file in my persistent data path. Added a check to make sure the file doesn't already exist before creating it. Also, make sure you create the directory in case it doesn't exist, else you'll get an error. Note that this solution is probably not optimal if you have large files that are regularly accessed.
string realPath = Application.persistentDataPath + "/PATH/" + fileName;
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PATH/"))
{
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PATH/");
}
WWW reader = new WWW(Application.streamingAssetsPath + "/PATH/" + realPath);
while ( ! reader.isDone) {}
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
Application.OpenURL(realPath);
If anyone has anything to add to this answer, feel free !

SaveFileDialog doesn't show any possible extensions despite using Filter option

I'm creating right now an application in C# which saves data to the file upon clicking a button. The name and locations of the file is defined by the user, and i want the program to automatically add .txt extension to the name, as well as show only 1 possible extensions in "save files as" combobox. I have this code:
SaveFileDialog Dialog1 = new SaveFileDialog();
Dialog1.DefaultExt = "txt";
Dialog1.Filter = "Pliki tekstowe | *.txt";
Dialog1.AddExtension = true;
private void button1_Click(object sender, EventArgs e)
{
if (Dialog1.ShowDialog() == DialogResult.OK)
{
System.IO.Stream fileStream = Dialog1.OpenFile();
System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream);
sw.WriteLine("Writing some text in the file.");
sw.WriteLine("Some other line.");
sw.Flush();
sw.Close();
}
this.Close();
}
But whenever i click the button, i have no options to choose from in the combobox, as well as the .txt extensions are not added to the file name in case the extensions is not specified by the user himself. I know i can somehow bypass that by checking if the user gave the proper extensions, and in case he didn't add ".txt" to the name but i really wanted to know, why that piecei of code doesn't function. Any help?
The problem is the space. Just change it to this:
Dialog1.Filter = "Pliki tekstowe|*.txt";
and you should be in business.
Otherwise it's trying to match files of the pattern  *.txt (subtly compared to *.txt) - which you probably don't have.
take a look at the following example and see the difference:
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx
you should try firstly to add this to your filter:
"txt files (*.txt)|*.txt|All files (*.*)|*.*"
for completeness you should add the (*.txt) string in your filter for descriptive reasons (thanks for clarifying Yuck). Try it - see what happens :)
remember it is sensitive in terms of the string. so try not to put things like a space between the file extensions
I had a similar issue where the save dialog box on firefox and safari doesn't detect the file extension even though I had Content-Type header set to "application/pdf". The issue turned out to be spaces in the name of the file. I replaced the file name with '-' (hyphens) and that fixed it.

How to open a PDF file that is also a project resource?

I have a PDF file that I have imported in as a resource into my project. The file is a help document so I want to be able to include it with every deployment. I want to be able to open this file at the click of a button.
I have set the build action to "Embedd Resource". So now I want to be able to open it. However, When I try accessing the resource - My.Resources.HelpFile - it is a byte array. How would I go about opening this if I know that the end-user has a program suitable to opening PDF documents?
If I missed a previous question please point me to the right direction. I have found several questions about opening a PDF within an application, but I don't care if Adobe Reader opens seperately.
Check this out easy to open pdf file from resource.
private void btnHelp_Click(object sender, EventArgs e)
{
String openPDFFile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\HelpDoc.pdf";//PDF DOc name
System.IO.File.WriteAllBytes(openPDFFile, global::ProjectName.Properties.Resources.resourcePdfFileName);//the resource automatically creates
System.Diagnostics.Process.Start(openPDFFile);
}
Create a new Process:
string path = Path.Combine(Directory.GetCurrentDirectory(), "PDF-FILE.pdf");
Process P = new Process {
StartInfo = {FileName = "AcroRd32.exe", Arguments = path}
};
P.Start();
In order for this to work, the Visual Studio setting Copy to Output Directory has to be set to Copy Always for the PDF file.
If the only point of the PDF is to be opened by a PDF reader, don't embed it as a resource. Instead, have your installation copy it to a reasonable place (you could put it where the EXE is located), and run it from there. No point in copying it over and over again.
"ReferenceGuide" is the name of the pdf file that i added to my resources.
using System.IO;
using System.Diagnostics;
private void OpenPdfButtonClick(object sender, EventArgs e)
{
//Convert The resource Data into Byte[]
byte[] PDF = Properties.Resources.ReferenceGuide;
MemoryStream ms = new MemoryStream(PDF);
//Create PDF File From Binary of resources folders helpFile.pdf
FileStream f = new FileStream("helpFile.pdf", FileMode.OpenOrCreate);
//Write Bytes into Our Created helpFile.pdf
ms.WriteTo(f);
f.Close();
ms.Close();
// Finally Show the Created PDF from resources
Process.Start("helpFile.pdf");
}
File.Create("temp path");
File.WriteAllBytes("temp path", Resource.PDFFile)
You need to convert the resource into format acceptable for the program supposed to consume your file.
One way of doing this is to write the content of the resource to a file (a temp file) and then launch the program pointing it to the file.
Whether it is possible to feed the resource directly into the program depends on the program. I am not sure if it can be done with the Adobe Reader.
To write the resource content to a file you can create an instance of the MemoryStream class and pass your byte array to its constructor
This should help - I use this code frequently to open various executable, documents, etc... which I have embedded as a resource.
private void button1_Click(object sender, EventArgs e)
{
string openPDFfile = #"c:\temp\pdfName.pdf";
ExtractResource("WindowsFormsApplication1.pdfName.pdf", openPDFfile);
Process.Start(openPDFfile);
}
void ExtractResource( string resource, string path )
{
Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
byte[] bytes = new byte[(int)stream.Length];
stream.Read( bytes, 0, bytes.Length );
File.WriteAllBytes( path, bytes );
}
//create a temporal file
string file = Path.GetTempFileName() + ".pdf";
//write to file
File.WriteAllBytes(file, Properties.Resources.PDF_DOCUMENT);
//open with default viewer
System.Diagnostics.Process.Start(file);

OpenFile dialog, Multiselect=true, i cannot reach files

private void btnNew_Click(object sender, System.Windows.RoutedEventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.Multiselect = true;
of.Filter = "JPG Dosyaları|*.jpg|JPEG Dosyaları|*.jpeg";
of.ShowDialog();
foreach (var file in of.Files)
{
MessageBox.Show(file.FullName);
}
}
The problem is i want to open multiple files' in Silverlight and i don't know any other way doing it than passing the filenames into a foreach loop. The problem is Silverlight don't like if i try to reach files in a loop, it must be a direct command from user.
In this case it throws an exception:
File operation not permitted
So is there another way manipulating local files (not from isolated space), or is there any way i can make this code work?
Thanks guys.
Don't use file.FullName to open the file. You get a FileInfo object back, use one of its OpenXxxx() methods to open the file.

Categories

Resources