StreamWriter trouble writing doubles to .txt file (C++) - io

I'm trying to write some double values to a text file the user creates via a SaveFileDialog, but everytime I do a streamWriterVariable->Write(someDoubleVariable), I instead see some kind of weird ASCII character in the text file where the double should be (music note, |, copyright symbol, etc). I'm opening the file with notepad if it's that of any significance. A basic outline of my code:
SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;
saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1->Title = "Save File Here";
saveFileDialog1->RestoreDirectory = true;
if (saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
FileInfo ^fleTest = gcnew FileInfo(saveFileDialog1->FileName);
StreamWriter ^sWriter = fleTest->CreateText();
sWriter->AutoFlush = true;
double test = 5.635; //Some arbitrary double I made up for test purposes
sWriter->Write(test);
sWriter->Flush();
sWriter->Close();
}
Thanks for your help!

Have you tried to set the encoding explicitly?
StreamWriter^ sWriter = gcnew StreamWriter(saveFileDialog1->FileName, false, System::Text::Encoding::ASCII);

The code you've provided does exactly what you ask it to, that is to write a double to the file in the internal computer format. What you most likely want it to write out the textual representation of the double.
In other words you should try sWriter->Write(test.ToString()) or some variation over this, to get the textual version of your double. This also applies to bool and most other variable representation.

Related

Save xlsl file with Hebrew as txt to load into Photoshop data sets

I have an Excel (xlsx) file that has 3 columns of data that is set to replace said data in a Photoshop file (PSD), to do so I need to load it into Photoshop in a txt format, encoded to ANSI, so that Photoshop can read that file, and export it a bunch of times each time with the next row's properties.
However my Excel file has some Hebrew text, that is lost when encoding to ANSI, I tried other encodings but Photoshop doesn't accept them, how can I still feed Photoshop with the Hebrew data? (It's a lot of photos so I can't do it manually one by one)
This works for me: I've got a simple text file, with some Hebrew text on it.
And from Photoshop:
var myfile = "D:\\temp\\hebrew.txt"; // change this
var text = read_it(myfile);
alert(text);
// השועל החום המהיר קופץ מעל הכלב העצלן.
// function READ IT (filename with path) :returns string
// ----------------------------------------------------------------
function read_it(afilepath)
{
var theFile = new File(afilepath);
//read in file
var words = ""; // text collection string
var theTextFile = new File(theFile);
theTextFile.open('r');
while(!theTextFile.eof)
{
var line = theTextFile.readln();
if (line != null && line.length >0)
{
words += line + "\n";
}
}
theTextFile.close();
// return string
return words;
}

X++ SysExcelWorkbook.saveAs - change encoding

I'm trying to convert XLS to CSV using job in AX2012. I have some non-ASCII characters in my XLS and I need to find out how can I set SysExcelWorkbook.saveAs method to use specific encoding (eg. UTF-8).
static void ExcelToCsv(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
FileName xlsFile, csvFile;
;
application = SysExcelApplication::construct();
application.displayAlerts(false);
workbooks = application.workbooks();
xlsFile = #"C:\test.xlsx";
csvFile = #"C:\result.csv";
workbooks.open(xlsFile);
workbook = workbooks.item(1);
workbook.saveAs(csvFile, 6);
// workbook.saveAs(resFile, 22);
// workbook.saveAs(resFile, 23);
// workbook.saveAs(resFile, 24);
application.quit();
}
The code above generates CSV, but all non-ASCII characters are not displaying property when opening in text editor. I expect that I will be able to choose encoding for my CSV file programmatically or use source (XSL) encoding. Is there a way to achieve this with X++?
I don't think you can do this without some workarounds as it appears to be an Excel limitation. It's do-able though if you really need it.
It uses the Excel COM object to do the work, and you can see the reference here, where I can't find any options to specify encoding:
https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.saveas
Here is the same issue, albeit in Powershell instead of X++ with solution (I think) being to export to UnicodeText instead of CSV, then replacing \t with , in the output file.
It looks like you could output to UnicodeText by making the below change to your code, then you could just use some other string-replace to update the final file.
#Excel
// workbook.saveAs(csvFile, 6); // 6 == #xlCSV
workbook.saveAs(csvFile, #xlUnicodeText);
I'm not sure if this truly fixes your encoding issue without testing. I'd also want to double-check how single/double quotes are handled.

Delete .csv-column without losing format

My file got the format Unix (LF) with UTF-8-BOM. It got quotation marks on each column:
Now i want to delete the last column. If i save the file with excel as .csv it is formatted in Windows (CR LF) in ANSI. It loses the quotation marks:
I wrote a short C# code to remove the last column manually with StreamReader/StreamWriter, but the output is also formatted in Windows (CR LF) UTF-8. Curiously it additionally loses some lines..
string newFilename = tboxFile.Text.Split(new string[] { ".csv" }, StringSplitOptions.None)[0] + "_replaced123.csv";
StreamReader streamReader = new StreamReader(tboxFile.Text);
StreamWriter streamWriter = new StreamWriter(newFilename);
string line = streamReader.ReadLine();
streamWriter.WriteLine(line.Split(new string[] { ";\"#timestamp\"" }, StringSplitOptions.None)[0]);
while ((line = streamReader.ReadLine()) != null)
streamWriter.WriteLine(line.Split(new string[] { ";\"2017-11-" }, StringSplitOptions.None)[0]);
So.. Is there a special excel-trick to save the output in same format (Unix LF UTF-8-BOM) or how can i help me?
Like my comment above says, the spreadsheet tool from LibreOffice offers to adjust filter settings when you do Save As on a csv file.
To get there check the box "Edit filter settings" in the Save As dialog. After pressing the save button a "Textexport" dialog will show up where you can select the text codec among other things.

write textbox data to text file

I have code that is supposed to take all the user data that was input after the program was run and put it all into a text file.
Here is the code so far:
protected void WriteFile(object sender, EventArgs e)
{
FileStream fs = new FileStream(#"C:\Users\4567\MyDocuments\ExporterOutput.txt", FileMode.OpenOrCreate, FileAccess.Write);
TextBox[] tbs = { username, TextBox2, sgml, Path };
StringBuilder sb = new StringBuilder();
foreach (TextBox tb in tbs)
sb.AppendLine(tb.Text);
sb.AppendLine(DropDownList1.SelectedItem.ToString());
sb.AppendLine(DropDownList2.SelectedItem.ToString());
System.IO.File.WriteAllText(#"C:/Users/4567/My Documents/ExporterOutput.txt", sb.ToString());
I tried running it and the text file just shows up blank. Can anyone tell me what I am doing wrong and if there is an easier way to output all textbox information to a text file. And preferrable in a certain format.
Here is the edited code from the suggestions you gave me:
protected void WriteFile(object sender, EventArgs e)
{
TextBox[] tbs = { username, TextBox2, sgml, Path };
StringBuilder sb = new StringBuilder();
foreach (TextBox tb in tbs)
sb.AppendLine(tb.Text);
sb.AppendLine(DropDownList1.SelectedItem.ToString());
sb.AppendLine(DropDownList2.SelectedItem.ToString());
System.IO.File.WriteAllText(#"C:\\Users\\oZ012D\\My Documents\\ExporterOutput.txt", sb.ToString());
}
Ok, Im going to take a few guesses here.
Your last line should be
System.IO.File.WriteAllText(#"C:\\Users\\4567\\My Documents\\ExporterOutput.txt", sb.ToString());
You are using windows, so you need the "\" char and not the forward slash like you would on Linux. This is accomplished by having the double backslash (which c# recognizes as a single backslash) in your string.
Also, try getting rid of your first line. You are creating a file stream and then not using or closing it. I think its possible that the open FS is causing issues.
Don't worry about creation issues, the WriteAllText() call will create the file if it doesn't exist and will overwrite it if it does.
Let me know if that works, the only other thing that looks potentially incorrect to me is the way you are getting text from the drop down menus.

PDF text search and split library

I am look for a server side PDF library (or command line tool) which can:
split a multi-page PDF file into individual PDF files, based on
a search result of the PDF file content
Examples:
Search "Page ???" pattern in text and split the big PDF into 001.pdf, 002,pdf, ... ???.pdf
A server program will scan the PDF, look for the search pattern, save the page(s) which match the patten, and save the file in the disk.
It will be nice with integration with PHP / Ruby. Command line tool is also acceptable. It will be a server side (linux or win32) batch processing tool. GUI/login is not supported. i18n support will be nice but no required. Thanks~
My company, Atalasoft, has just released some PDF manipulation tools that run on .NET. There is a text extract class that you can use to find the text and determine how you will split your document and a very high level document class that makes the splitting trivial. Suppose you have a Stream to your source PDF and an increasingly ordered List that describes the starting page of each split, then the code to generate your split files looks like this:
public void SplitPdf(Stream stm, List<int> pageStarts, string outputDirectory)
{
PdfDocument mainDoc = new PdfDocument(stm);
int lastPage = mainDoc.Pages.Count - 1;
for (int i=0; i < pageStarts.Count; i++) {
int startPage = pageStarts[i];
int endPage= (i < pageStarts.Count - 1) ?
pageStarts[i + 1] - 1 :
lastPage;
if (startPage > endPage) throw new ArgumentException("list is not ordered properly", "pageStarts");
PdfDocument splitDoc = new PdfDocument();
for (j = startPage; j <= endPage; j++)
splitDoc.Pages.Add(mainDoc.Pages[j];
string outputPath = Path.Combine(outputDirectory,
string.Format("{0:D3}.pdf", i + 1));
splitDoc.Save(outputPath);
}
if you generalize this into a page range struct:
public struct PageRange {
public int StartPage;
public int EndPage;
}
where StartPage and EndPage inclusively describe a range of pages, then the code is simpler:
public void SplitPdf(Stream stm, List<PageRange> ranges, string outputDirectory)
{
PdfDocument mainDoc = new PdfDocument(stm);
int outputDocCount = 1;
foreach (PageRange range in ranges) {
int startPage = Math.Min(range.StartPage, range.EndPage); // assume not in order
int endPage = Math.Max(range.StartPage, range.EndPage);
PdfDocument splitDoc = new PdfDocument();
for (int i=startPage; i <= endPage; i++)
splitDoc.Pages.Add(mainDoc.Pages[i]);
string outputPath = Path.Combine(outputDirectory,
string.Format("{0:D3}.pdf", outputDocCount));
splitDoc.Save(outputPath);
outputDocCount++;
}
}
PDFBox is a Java library but it does have some command line tools as well:
http://pdfbox.apache.org/
PDFBox can extract text and also rebuilt/split PDFS
pdfminer + multi-line pattern matching in python
You can use pdfsam to split your file in pages, then use pdftotext (from foolabs.com) to turn this into text and use ruby (or grep) to find the strings. Then you have the page ranges and can return the previous generated pages.

Resources