110,539
社区成员
发帖
与我相关
我的任务
分享
if (File.Exists(path4))
{
FileStream fs1 = new FileStream(path4, FileMode.Open, FileAccess.Write,FileShare.ReadWrite);
BinaryWriter bw1 = new BinaryWriter(fs1);
//fs1.Seek(0, SeekOrigin.End);
fs1.Seek(i, SeekOrigin.Begin);
bw1.Write(Buf_DC_A[i]);//
bw1.Flush();
bw1.Close();
fs1.Close();
}
else
{
FileStream fs1 = new FileStream(path4, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
BinaryWriter bw1 = new BinaryWriter(fs1);
//fs1.Seek(0, SeekOrigin.End);
fs1.Seek(i, SeekOrigin.Begin);
bw1.Write(DC_A[);//
bw1.Flush();
bw1.Close();
fs1.Close();
}
,这是写文件,DC_A是数据,i是当前时间转化为的秒。
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
fs.Seek(t1, SeekOrigin.Begin);
br.Read(buf, t1, s * 4);
,这是读文件。t1是选择启示时间的秒数。using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace DataSaveRead
{
[Serializable]
public class DataClass
{
public int SerialNumb{get;set;}
public int DataValue{get;set;}
public DataClass(int n,int d)
{
SerialNumb = n;
DataValue = d;
}
}
class Program
{
static void Main(string[] args)
{
List<DataClass> SaveList = new List<DataClass>();
List<DataClass> ReadList = new List<DataClass>();
int i=0;
int d=100;
int Index;
int IndexRange;
int ValueOfIndex;
int[] ValueOfArray;
Console.WriteLine("Input the file path");
string path = Console.ReadLine() + ".txt";
#region Save
Console.WriteLine("***Begin to Save***");
for (int c = 0; c < 100; c++)
{
SaveList.Add(new DataClass(i++, d++));
}
using (FileStream ms = File.Create(path))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, SaveList);
}
Console.WriteLine("***End Save***");
#endregion
#region Read
Console.WriteLine("***Begin to Read***");
using (FileStream ms = File.OpenRead(path))
{
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(ms);
if (obj is List<DataClass>)
{
ReadList = obj as List<DataClass>;
#region Read one data
Console.WriteLine("Input the data index");
Index = Convert.ToInt32(Console.ReadLine());
var result = from n in ReadList
where n.SerialNumb == Index
select n.DataValue;
ValueOfIndex = result.ElementAt(0);
Console.WriteLine("Index={0},Value={1}", Index, ValueOfIndex);
#endregion
#region Read dataArray
Console.WriteLine("Input the data index Range:Form 0 to ?");
IndexRange = Convert.ToInt32(Console.ReadLine());
ValueOfArray = new Int32[IndexRange];
var resultArray = from n in ReadList
where n.SerialNumb <= IndexRange
select n.DataValue;
Console.WriteLine("***Index Form 0 to {0} are as follow***", IndexRange);
ValueOfArray = resultArray.ToArray();
foreach (int va in ValueOfArray)
{
Console.WriteLine("Value={0}", va);
}
#endregion
}
else
{
return;
}
}
#endregion
Console.ReadKey();
}
}
}