C#: StreamWriter program is not writing to text file - c#

I know this question has probably been answered multiple times across this site, but even after looking at those solutions I don't have an answer to why my program isn't writing to the text file I have assigned. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Main
{
class Program
{
public static void Main (string[] args)
{
using (StreamWriter writer = new StreamWriter("test.txt"))
{
writer.WriteLine("Hello, World!");
}
}
}
}
My program throws no exceptions and exits with 0, so I am not understanding how this is still not functioning properly. If someone could please provide an answer along with an explanation as to why this doesn't work, I would really appreciate it.
EDIT: Okay, I fixed the code after playing around a bit. Turns out that upon reading the file the text that I wrote is there. Thus, a clarification of this problem would be:
The text writes to the file, but it is not visible to me when I open up the file from my project in Visual Studio. I am not sure as to why, and this is leading to confusion

Your sample is correct. The file is saved into build path. (where is "yourApp.exe").
You can try with a abosule path to define where file will be save, for example StreamWriter writer = new StreamWriter(#"c:\test\test.txt")

Related

Convert .doc to .docx using C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I convert PDF file to the word file using PDFFocus.net dll. But for my system I want .docx file. I tried different ways. There some libraries available. But those are not free. This is my pdf to doc convert code.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using iTextSharp.text;
Using iTextSharp.text.pdf;
namespace ConsoleApplication
{
class Program
{
static void main(String[] args)
{
SautinSoft.PdfFocus f=new SautinSoft.PdfFocus();
f.OpenPdf(#"E:\input.pdf");
t.ToWord(#"E:\input.doc");
}
}
}
This work successfully.
Then I tried with below code to convert .doc to .docx. But it gives me error.
//Open a Document.
Document doc=new Document("input.doc");
//Save Document.
doc.save("output.docx");
Can anyone help me please.
Yes like Erop said. You can use the Microsoft Word 14.0 Object Library. Then it's really easy to convert from doc to docx. E.g with a function like this:
public void ConvertDocToDocx(string path)
{
Application word = new Application();
if (path.ToLower().EndsWith(".doc"))
{
var sourceFile = new FileInfo(path);
var document = word.Documents.Open(sourceFile.FullName);
string newFileName = sourceFile.FullName.Replace(".doc", ".docx");
document.SaveAs2(newFileName,WdSaveFormat.wdFormatXMLDocument,
CompatibilityMode: WdCompatibilityMode.wdWord2010);
word.ActiveDocument.Close();
word.Quit();
File.Delete(path);
}
}
Make sure to add CompatibilityMode: WdCompatibilityMode.wdWord2010 otherwise the file will stay in compatibility mode. And also make sure that Microsoft Office is installed on the machine where you want to run the application.
Another thing, I don't know PDFFocus.net but have you tried converting directly from pdf to docx. Like this:
static void main(String[] args)
{
SautinSoft.PdfFocus f=new SautinSoft.PdfFocus();
f.OpenPdf(#"E:\input.pdf");
t.ToWord(#"E:\input.docx");
}
I would assume that this is working, but it's only an assumption.
Try to use Microsoft.Office.Interop.Word assembly.
An MSDN article can be found Here
Include references in your project, and enable their use in a code module via an example from the above link that shows
using System.Collections.Generic;
using Word = Microsoft.Office.Interop.Word;

C# how do I draw on files in the same location as i'm running the program without a long path

So far I haven't found anything that would allow my program to access text files that are in the same folder as it.
for example:
if my file is in C:/testingfolder i would need to use C:/testingfolder/filenames.txt to access the other files, the problem with this is sometimes it wont be in c:/testingfolder but instead it might be in E:/importantfiles or F:/backup and it needs to run from all of those.
If anyone could explain or give code that showed how to make a longer path into a "same folder" path that would answer my question.
With the Environment.CurrentDirectory you can get the path of your process that is executing, then you should use System.IO.Path.Combine() method to concatenate this path with the name of your file, and you will get the absolute location of your file.
You need to use System.IO and System.Text
using System;
using System.IO;
using System.Text;
then
static void Main(string[] args)
{
string line = "";
// look for the file "myfile.txt" in application root directory
using (StreamReader sr = new StreamReader("myfile.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}

System IO Exception was unhandled

I'm trying to develop my first application in C#, and I'm simply trying to read and write from a file. I've done hours of research, had mentors attempt to teach me, but its just not making sense to me.
I've got the beginning of my Form laid out, and what I believe to be the correct syntax for the StreamWriter I'm using, but the file name seems to be used in another process, and I have no idea which. Here's the code I'm working with:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace CustomerApplication
{
public partial class AddCustomerForm : Form
{
public AddCustomerForm()
{
InitializeComponent();
}
private void saveAndExitBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = File.AppendText("test.csv");
sw.WriteLine("Test for Hope");
// next, retrieve hidden form's memory address
Form myParentForm = CustomerAppStart.getParentForm();
// now that we have the address use it to display the parent Form
myParentForm.Show();
// Finally close this form
this.Close();
}// end saveAndExitBtn_Click method
This is the line that Visual Studio doesn't like :
StreamWriter sw = File.AppendText("test.csv");
Thanks for your time, in advance.
~TT
Educated guess here (based on but the file name seems to be used in another process) - you open the file for writing, but you never close it. So when you later try to write to it again, it fails.
Note that this can also happen if you have the file open in some other application (notepad, for instance).
You should be placing the creation of the stream in a using statement to ensure it gets closed when you finish working with it:
using(StreamWriter sw = File.AppendText("test.csv")
{
sw.WriteLine("Test for Hope");
...
}
Are you sure you are not holding open the file somewhere else? For example before you step into that line of code you can try and delete the file manually to see if some process is holding onto it. I typed it in and it worked. I would recommend wrapping the Streamwriter in a using statement though and using the FileInfo object. The FileInfo object has a few nice properties on it like you can test to see if the file exists. You can do something like this also.
FileInfo fi = new FileInfo("C:\\test.csv");
if (fi.Exists)
using (Streamwriter sw = fi.AppendText())
{
sw.WriteLine("tst");
sw.Close();
}

Using embedded resources in C# console application

I'm trying to embed an XML file into a C# console application via Right clicking on file -> Build Action -> Embedded Resource.
How do I then access this embedded resource?
XDocument XMLDoc = XDocument.Load(???);
Edit: Hi all, despite all the bashing this question received, here's an update.
I managed to get it working by using
XDocument.Load(new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Namespace.FolderName.FileName.Extension")))
It didn't work previously because the folder name containing the resource file within the project was not included (none of the examples I found seemed to have that).
Thanks everyone who tried to help.
Something along these lines
using System.IO;
using System.Reflection;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.XMLFile1.xml");
StreamReader reader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
}
}
}
Here is a link to the Microsoft doc that describes how to do it. http://support.microsoft.com/kb/319292

C# PDF library for headless Linux server

I'm currently trying to find a PDF library which will run without a running X server. I have already tried the following...
Migradoc/PDFSharp (requires X)
ITextSharp (requires X)
SharpPDF (might work, but I am looking for something with a bit more features)
The library does not have to be opensource or free.
My solution runs on Apache2.2 mod_mono.
Does anyone know of such library?
--- edit ---
The test code used for itextsharp, which produces errors on my testserver is listed below (the code for Migradoc and SharpPDF is just as simple):
using System;
using sharp=iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.IO;
namespace pdftester
{
public static class ITextSharpTest
{
public static void HelloWorld(string filename)
{
Stream stream = new FileStream(filename, FileMode.Create);
sharp.Document document = new sharp.Document();
PdfWriter.GetInstance(document, stream);
document.Open();
document.Add(new sharp.Paragraph("Hello world"));
document.Close();
}
}
}
Since no one has given a definitive answer to the thread, i'm closing it.
I've chosen to go the sharpPDF way, as it's the only one supported on my server. I'll simply have to implement what's needed for my project.
Thanks for the help received so far :)

Categories