I want to save integer or double value in file ?? I have done to put string by this method - c#-3.0

string example="Example";
System.IO.File.WriteAllText(#"C:\WriteText.txt", text);
string output = system.Io.file.Readalltext(#"C:/example.txt");
console.write("output"+output);

using System.IO; //to access the StreamWriter and StreamReader Class.
//to write item to the file
string myPath = #"C:/example.txt"; //this is where you put the text.
StreamWriter sw = new StreamWriter(myPath);
sw.Write("write something");
sw.Close();
//to read the item in the file
string myPath = #"C:/example.txt"; //this is where you read the text.
StreamReader sr = new StreamReader(myPath);
string item = sr.ReadToEnd();
Console.WriteLine(item);
sr.Close();

Related

How to convert an array of stream in Contents to PRIndirectRefernce?

I am trying to read pdf and get the text present in it. Using Nugget iTextSharp -LGPL v4.1.5 . (I am not allowed to use ITextsharp v5.5.13 and it makes life difficult)
private string GetTextFromPage(PdfReader pdfReader, int page)
{
StringBuilder pageText = new StringBuilder();
var cpage = pdfReader.GetPageN(page);
var content = cpage.Get(PdfName.CONTENTS);
//Error for casting Pdfarray to PRIndirectReference
var indirectReference = (PRIndirectReference)content;
}
Getting Exception
System.InvalidCastException : Unable to cast object of type 'iTextSharp.text.pdf.PdfArray' to type 'iTextSharp.text.pdf.PRIndirectReference'.
Kindly suggest how to handle PdfArray object (multiple streams in contents)
I am not too versed in c# but the java code should be easily transferable to c#
I would do it like this:
private byte[] getTextFromPage(PdfReader pdfReader, int page){
PdfDictionary cpage = pdfReader.GetPageN(page);
PdfObject content = cpage.get(PdfName.CONTENTS);
return getContent(content);
}
private byte[] getContent(PdfObject content) throws IOException {
byte[] result=null;
switch (content.type()){
case PdfObject.INDIRECT:
PRIndirectReference ref = (PRIndirectReference) content;
PdfObject directObject = PdfReader.getPdfObject(ref);
result = getContent(directObject);
break;
case PdfObject.ARRAY:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfArray cArray = (PdfArray) content;
for(Object object : cArray.getArrayList()) {
baos.write(getContent((PdfObject) object));
}
result = baos.toByteArray();
break;
case PdfObject.STREAM:
PRStream stream = (PRStream) PdfReader.getPdfObject(content);
result = PdfReader.getStreamBytes(stream);
break;
default:
throw new IllegalStateException("Unsupported content type");
}
return result;
}
But this is only a small step in retrieving the text. You need the whole operator processing, leading, spacing, scaling, font handling etc. So to completely write it from scratch is a big task...

Hi All, I am struggling in rest API where i need to post an XML in body with header and get the response, can anyone post an example of how to do it?

String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it
You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}

Changes made in text file (programatically ) are not reflected back

I have following code. On making changes in the text file when I open the file I can't see any change in fact the text of text file is removed.
private void btnGo_Click(object sender, EventArgs e)
{
string content;
string newword = "Tanu";
string oldword = "Sunrise";
System.IO.StreamReader file =
new System.IO.StreamReader(txtFilePath.Text);
while ((content = file.ReadLine()) != null)
{
if (content == "Project name = Sunrise ")
{
string newtxt = Regex.Replace(content, oldword, newword);
content = content.Replace(content, newtxt);
}
// counter++;
}
file.Close();
using (StreamWriter writer = new StreamWriter(txtFilePath.Text))
{
writer.Write(content);
writer.Close();
Error is in your while loop.
while ((content = file.ReadLine()) != null)
after replacing content with newtxt while is executing again and is trying to read next line in file which is setting content to null and so when you come out of while loop your content is null.
try reading file content into a different variable or use say newtxt itself to write to file.

parsing a string using a Lucene Analyser

How can you use an Analyser to 'analyse' a string, and return the analysed string?
I am trying the below code found off this site, but it is throwing an ArgumentException - "This AttributeSource does not have the attribute Lucene.Net.Analysis.Tokenattributes.TermAttribute"
public static string AnalyseString(Analyzer analyser, string stringToAnalyse)
{
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.Write(stringToAnalyse);
sw.Flush();
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
TokenStream tokenStreamResult = analyser.TokenStream(null,sr);
StringBuilder sb = new StringBuilder();
//Lucene.Net.Analysis.Token t = new Lucene.Net.Analysis.Token();
while (tokenStreamResult.IncrementToken())
{
var attrib = tokenStreamResult.GetAttribute<TermAttribute>();
string t2 = tokenStreamResult.GetAttribute<TermAttribute>().Term;
sb.Append(t2 + " ");
}
return sb.ToString();
}
I am using the latest Lucene.Net version (3.0.3.0), and am testing with a SimpleAnalyzer
Try tokenStreamResult.GetAttribute<ITermAttribute>() instead

saving email attachments as binary to the database using c#

I can get email attachments from exchange server 2003 (MAPI.Attachment). How can I save the pdf attachment file as binary into the database?
Here's some code to understand better. For testing purposes I am saving the attachment pdf file into a filesystem. How ca I go about saving that into a database? Or how can I convert that into a byte array? Also, how can I get the size of the file since I need that when I declare the byte array "fileData"...
byte[] fileData = new byte[10000];
string[] fileTokens = new string[2];
string[] result = new string[3];
message.Unread = false;
emailSubject = message.Subject.ToString();
emailBody = message.Text.ToString();
MAPI.Attachments test = null;
test = (MAPI.Attachments)message.Attachments;
int attachmentCount = (int)test.Count;
for (int loopCounter = 1; loopCounter <= attachmentCount; loopCounter++)
{
MAPI.Attachment test2 = (MAPI.Attachment)test.get_Item(loopCounter);
bool temp = (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0);
if (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0)
{
//test2.ReadFromFile(fileData);
test2.WriteToFile("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
}
RequestHistorySet historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);
bool res = historySet.Update();
message.Unread = false;
message.Update();
And here's the Update function from historySet Class
public bool Update()
{
using (SqlConnection mySqlConnection = ...))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("CONNECTION STRING..", mySqlConnection);
// Set up the OriginalName parameter
SqlParameter prmId = new SqlParameter("#id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
SqlParameter prmRequsetDate = new SqlParameter("#requestDate", SqlDbType.DateTime);
prmRequsetDate.Value = requestDate;
myCommand.Parameters.Add(prmRequsetDate);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("#uplodedQuote_File ", SqlDbType.VarBinary);
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
myCommand.Parameters.Add(prmFileData);
SqlParameter prmFileExtension = new SqlParameter("#uplodedQuote_Ext", SqlDbType.NVarChar);
prmFileExtension.Value = fileExtension;
myCommand.Parameters.Add(prmFileExtension);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
return result;
}
}
As of now this is what I have done. I save it to a filesystem and then read from there.
test2.WriteToFile("d:\\data\\" + test2.Name);
fileData = FileToByteArray("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
TryToDelete("d:\\data\\" + test2.Name);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);