Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All i am develop one program get data from com port and save in txt file so i am able to do this but i don't know how can overwrite i need only single record when i am run my exe file(in console application with c# code).MY code as below for file save.
C#
if (string.IsNullOrEmpty(indata))
            {
                StreamWriter sw = new StreamWriter(@"c:\arjun.txt", true);
                sw.WriteLine("0");
                sw.Close();
            }
Posted
Comments
Arjunwalmiki 15-Dec-12 4:31am    
<pre lang="c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;



namespace PortDataReceived
{
class Program
{
static void Main(string[] args)
{
SerialPort mySerialPort = new SerialPort("COM1");
if (mySerialPort.IsOpen == true) mySerialPort.Close();
mySerialPort.BaudRate = 2400;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
mySerialPort.ReadTimeout = 500;
string indata = mySerialPort.ReadExisting();
if (string.IsNullOrEmpty(indata))
{
FileStream fs = new FileStream(@"c:\arjun.txt",FileMode.Append,FileAccess.Write);
try
{

StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("0");
sw.Close();
}
finally
{
fs.Close();
}

}
else
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < indata.Length; i += 8)
{

string section = indata.Substring(i, 8);

int ascii = 0;
try
{
ascii = Convert.ToInt32(section, 2);
}
catch
{
Console.WriteLine("Current Weight : " + section.ToString());
FileStream fs = new FileStream(@"c:\arjun.txt", FileMode.Append, FileAccess.Write);
try
{
StreamWriter sw = new StreamWriter(fs);

foreach (char c in section)
{
if (Char.IsLetterOrDigit(c))
{
builder.Append(c);
}
}

sw.WriteLine(builder.ToString());
sw.Close();
break;
}
finally
{
fs.Close();

}

}

}
}
// Console.WriteLine(builder.ToString());
Console.WriteLine(indata);
Console.WriteLine("Data Received:");
Console.Write(indata);
Console.ReadKey();
mySerialPort.Close();
}
}
}


</pre>


hello all the above is my code in this code i am read data from com port but problem is i was received 6 to 7 zero than received actual data from comport i was not under what was problem in my code pls let me know i was very thank full to all.i want solution on priority pls

1 solution

If you need to overwrite the file, specify false as second parameter of the StramWriter constructor, see the documentation[^].
 
Share this answer
 
Comments
codeninja-C# 7-Dec-12 5:50am    
+5 great

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900