我正在制作一个可以检测右臂关节坐标的Kinect应用程序;现在我想将这个坐标数据保存在一个文件中,无论是txt还是csv,但我不知道怎么做,有人能帮助我吗?我在c#
中使用Kinect SDK v1.8希望你能帮助我
答案 0 :(得分:0)
您可以使用带有关节对象列表的DataContract装饰创建一个支持类,然后随意加载和保存它们......
对于对象序列化,我通常在System.Runtime.Serialization.Json中使用DataContractJsonSerializer。这是一个例子。
[DataContract]
class ExampleSaveableClass
{
[DataMember]
public List<ExampleElements> _elements;
public ExampleSaveableClass()
{
_elements = new List<ExampleElements>();
}
internal static ExampleSaveableClass FromJsonString(string jsonString)
{
ExampleSaveableClass loadedSavableClass = Deserialize<ExampleSaveableClass>(jsonString);
return loadedSavableClass;
}
private static T Deserialize<T>(string json)
{
var instance = Activator.CreateInstance<T>();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(instance.GetType());
return (T)serializer.ReadObject(ms);
}
}
internal string ToJsonString()
{
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(ExampleSaveableClass));
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
然后在您的应用中,您可以......
{
private void ShowExportDialog(ExampleSaveableClass myClass)
{
var dlg = new Microsoft.Win32.SaveFileDialog();
dlg.Title = "Filename and Location to Export Sample Objects";
dlg.FileName = "MySavedObjects"; // Default file name
dlg.DefaultExt = ".json"; // Default file extension
dlg.Filter = "JSON documents (.json)|*.json"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
string str = myClass.ToJsonString();
System.IO.File.WriteAllText(dlg.FileName, str, Encoding.UTF8);
}
}
public static ExampleSaveableClass ImportSavedClass()
{
//Pseudo obtain filename...
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Event"; // Default file name
dlg.DefaultExt = ".json"; // Default file extension
dlg.Filter = "JSON documents (.json)|*.json"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result != true)
{
return null;
}
string filename = dlg.filename;
ExampleSaveableClass loadedSaveableClass = null;
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.Open);
var ds = new DataContractJsonSerializer(typeof(ExampleSaveableClass));
loadedSaveableClass = (ExampleSaveableClass)ds.ReadObject(fs);
}
finally
{
if(null != fs)
{
fs.Close();
}
}
return loadedSaveableClass;
}
}