如何写入配置文件 [英] How to write to config file

查看:106
本文介绍了如何写入配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨,,

我有两个问题:


1)桌面应用程序的配置文件是否必须是

App.config


2)是否可以在代码中更新配置文件?


感谢您的帮助。

ALI

解决方案

只需根据需要创建自己的强类型。以下可以

我也用加密和/或ISO存储等进行了修改。


MyAppConfig mac = new MyAppConfig();

mac.X = 20;

mac.Y = 40;

mac.Save();

MyAppConfig mac2 = MyAppConfig.Load ();

Console.WriteLine(" Name:" + mac2.Name);

Console.WriteLine(" X:" + mac2.X) ;

Console.WriteLine(" Y:" + mac2.Y);

使用System;

使用System.Xml.Serialization ;

使用System.IO;

使用System.Reflection;


命名空间MyNamespace

{

///< summary>

/// MyAppSettings的摘要说明。

///< / summary>

公共密封类MyAppConfig

{

公共字符串名称;

public int X;

public int Y;

// ...添加其他人...


私有静态只读字符串文件;


静态MyAppConfig()

{

file = Assembly.GetExecutingAssembly()。Location +" .xml";

}


public MyAppConfig()

{

Name = Assembly.GetExecutingAssembly()。GetName()。Name;

}

public static MyAppConfig Load()

{

using(StreamReader sr = new StreamReader(MyAppConfig.file))

{

string xml = sr.ReadToEnd();

MyAppConfig mac = MyAppConfig.FromXmlString(xml);

返回mac;

}

}


public void保存()

{

string myXml = this.ToXmlString();

使用(StreamWriter sw = new StreamWriter(MyAppConfig.file))

{

sw.Write(myXml) );

}

}


公共字符串ToXmlString()

{

string data = null;

XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));

using(StringWriter sw = new StringWriter())

{

ser.Serialize(sw,this);

sw.Flush();

data = sw.ToString();

返回数据;

}

}


public static MyAppConfig FromXmlString(string xmlString)

{

if(xmlString == null)

抛出新的ArgumentNullException(" xmlString");


MyAppConfig mac = null;

XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));

using(StringReader sr = new StringReader(xmlString))

{

mac =(MyAppConfig)ser.Deserialize(sr);

}

返回mac;

}

}

}

-

William Stacey,MVP
http://mvp.support.microsoft.com

" ALI-R" <是ne **** @ microsoft.com>在消息中写道

新闻:eG ************** @ TK2MSFTNGP14.phx.gbl ...

嗨,,
我有两个问题:

1)桌面应用程序的配置文件必须是必须的吗
App.config

2)是否可以在您的代码中更新配置文件??

感谢您的帮助。
ALI




此版本使用静态方法和ISO存储进行装配设置。

可能更有用,无需担心文件路径位置

或用户步进在文件上。范围是汇编和用户特定的因此

不同的用户可以有不同的设置。新的组装版本将

也有自己的设置而不会相互冲突(即用户运行并行版本的
。)


用法示例:

-------------------------

MyAssemConfig mac = MyAssemConfig。 GetAssemConfig();

mac.X = 20;

mac.Y = 40;

MyAssemConfig.SetAppConfig(mac);


MyAssemConfig mac2 = MyAssemConfig.GetAssemConfig();

Console.WriteLine(" Name:" + mac2.Name);

Console.WriteLine(" X:" + mac2.X);

Console.WriteLine(" Y:" + mac2.Y);


班级:

---------------------

使用系统;

使用System.Xml.Serialization;

使用System.IO;

使用System.IO.IsolatedStorage;

使用System.Reflection ;


命名空间MyNamespace

{

///< summary>

/// MyAppSettings的摘要说明。

/// < / summary>

公共密封类MyAssemConfig

{

公共字符串名称;

public int X;

public int Y;

// ...添加其他...


//私有静态只读字符串文件;

私有静态只读字符串isoFileName;


静态MyAssemConfig()

{

//文件= Assembly.GetExecutingAssembly()。Location +" .xml";

isoFileName =" AssemConfig.xml";

}


public MyAssemConfig()

{

Name = Assembly.GetExecutingAssembly()。GetName()。Name;

}


公共静态MyAssemConfig重置()

{

MyAssemConfig mac = new MyAssemConfig();

MyAssemConfig。 SetAppConfig(mac);

返回mac;

}


public static MyAssemConfig GetAssemConfig()

{

IsolatedStorageFile isoStore =

IsolatedStorageFile.GetStore(隔离StorageScope。汇编|

IsolatedStorageScope.User,null,null);


if(!MyAssemConfig.ISOFileExists(isoStore,isoFileName))

返回新的MyAssemConfig();


string xml = MyAssemConfig.ReadFromISOFile(isoStore,isoFileName);

try

{

MyAssemConfig mac = MyAssemConfig.FromXmlString(xml);

返回mac;

}

catch

{

// Xml无效 - 可能已损坏。用默认值重写它。

返回MyAssemConfig.Reset();

}

}


public static void SetAppConfig(MyAssemConfig appConfig)

{

if(appConfig == null)

抛出新的ArgumentNullException(" appConfig");

string xml = appConfig.ToXmlString();


IsolatedStorageFile isoStore =

IsolatedStorageFile.GetStore(IsolatedStorageScope。组装|

IsolatedStorageScope.User,null,null);

MyAssemConfig.WriteToISOFile(isoStore,isoFileName,xml);

}

// public static MyAppConfig Load()

// {

//使用(StreamReader sr = new StreamReader(MyAppConfig.file))

// {

//字符串xml = sr.ReadToEnd();

// MyAppConfig mac = MyAppConfig.FromXmlString(xml);

//返回mac;

//}

//}


// public void Save( )

// {

// string myXml = this.ToXmlString();

//使用(StreamWriter sw = new StreamWriter(MyAppConfig.file))

// {

// sw.Write(myXml);

//}

//}


公共字符串ToXmlString( )

{

string data = null;

XmlSerializer ser = new XmlSerializer(typeof(MyAssemConfig));

使用(StringWriter sw = new StringWriter())

{

ser.Serialize(sw,this);

sw.Flush() ;

data = sw.ToString();

返回数据;

}

}


public static MyAssemConfig FromXmlString(string xmlString)

{

if(xmlString == null)

throw new ArgumentNullException(" xmlString");


MyAssemConfig mac = null;

XmlSerializer ser = new XmlSerializer(typeof(MyAssemConfig));

using(StringReader sr = new StringReader(xmlString))

{

mac =(MyAssemConfig)se r。反序列化(sr);

}

返回mac;

}


私有静态bool ISOFileExists(IsolatedStorageFile isoStore,string

fileName)

{

if(isoStore == null)

throw new ArgumentNullException(" isoStore");

if(fileName == null || fileName.Length == 0)

返回false;


string [] names = isoStore.GetFileNames(" *");

foreach(名称中的字符串名称)

{

if(string.Compare(name,fileName,true)== 0)

返回true;

}

返回false;

}


private static void WriteToISOFile (IsolatedStorageFile isoStore,string

fileName,string data)

{

//将编写器分配给商店和文件TestStore。 />
使用(StreamWriter writer = new StreamWriter(new

IsolatedStorageFileStream(fileName,FileMode.Create,isoStore)))

{

//让作者写Hello Isolated Storage到商店。

writer.Write(数据);

}

}


私人静态字符串ReadFromISOFile(IsolatedStorageFile isoStore,string

fileName)

{

string sb = null;

//此代码打开TestStore.txt文件并读取字符串。

using(StreamReader reader = new StreamReader(new

IsolatedStorageFileStream(fileName,FileMode.Open,isoStore)))

{

sb = reader.ReadToEnd();

}

返回sb.ToString(); < br $>
}

}

}


-

William Stacey ,MVP
http://mvp.support.microsoft.com


" William Stacey [MVP]" < ST *********** @ mvps.org>在消息中写道

新闻:#j ************** @ TK2MSFTNGP15.phx.gbl ...

只需创建自己的根据需要提供强大的类型。以下内容也可以通过加密和/或ISO存储等进行修改。

MyAppConfig mac = new MyAppConfig();
mac.X = 20;
mac.Y = 40;
mac.Save();
MyAppConfig mac2 = MyAppConfig.Load();
Console.WriteLine(" Name:" + mac2.Name); < /> Console.WriteLine(" X:" + mac2.X);
Console.WriteLine(" Y:" + mac2.Y);

using System;
使用System.Xml.Serialization;
使用System.IO;
使用System.Reflection;

命名空间MyNamespace
{
// /< summary>
/// MyAppSettings的摘要说明。
///< / summary>
公共密封类MyAppConfig
{public string Name;
public int X;
public int Y;
// ...添加其他...

私有静态只读字符串文件;

static MyAppConfig()
{
file = Assembly.GetExecutingAssembly()。Location +" .xml";
}

公开MyAppConfig()
{Name = Assembly.GetExecutingAssembly()。GetName()。Name;
}
公共静态MyAppConfig Load()
{
使用(StreamReader sr = new StreamReader(MyAppConfig.file))
{x /> string xml = sr.ReadToEnd();
MyAppConfig mac = MyAppConfig.FromXmlString(xml); <返回mac;
}

公共无效保存()
{
字符串myXml = this.ToXmlString();
使用(StreamWriter sw = new StreamWriter(MyAppConfig.file))
{
sw.Write(myXml);
}
}

公共字符串ToXmlString()
{
字符串数据= null;
XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));
使用(StringWriter sw = new StringWriter())
{
ser.Serialize(sw,this);
sw.Flush();
data = sw.ToString();
返回数据;
}
}
公共静态MyAppConfig FromXmlString(字符串xmlString)
{
if(xmlString == null)
抛出新的ArgumentNullException(" xmlString");

MyAppConfig mac = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));
using(StringReader sr = new StringReader(xmlString))
{
mac =(MyAppConfig)ser.Deserialize(sr);
}
返回mac;
}
}

-
William Stacey,MVP
http://mvp.support.microsoft.com

ALI -R" <是ne **** @ microsoft.com>在消息中写道
新闻:eG ************** @ TK2MSFTNGP14.phx.gbl ...

嗨,,
我有两个问题:

1)桌面应用程序的配置文件必须是必须的吗
App.config

2)是否可以更新配置文件您的代码?

感谢您的帮助。
ALI




" ALI-R"写道:

1)必须是桌面应用程序的配置文件必须是
App.config


这是一个Visual Studio-ism 。这不是配置文件的结束

被调用,这就是它在Visual Studio .NET

项目中调用的内容。


如果你查看构建输出目录(用于C#项目的bin \Release或bin \Debug

目录,VB.NET项目的bin目录)你'会看到

有一个名为MyApp.exe.config的文件,其中MyApp.exe是你选择调用应用程序可执行文件的任何内容。


此Whatever.exe.config文件是App.Config文件的副本。 VS.NET

复制它,这样你就不需要保持单独的调试并释放这个文件的
版本。他们使用名称App.config,因为这是他们为此行为选择的

魔术名称。 :-)

2)是否可以在代码中更新配置文件?




有时是,但并非总是如此,所以你不应该依赖能够做到这一点




为什么你可能无法做到?请记住,配置文件最终位于

与可执行文件相同的目录中。如果它是作为普通的

Windows应用程序安装的,这将类似于c:\Program

Files \Yourcompany\Yourapp。


普通用户将无法写入此目录。 (至少没有,如果它是在NTFS卷上。)Windows保护Program Files目录,所以

只允许管理员和高级用户写入。


因此,如果您依赖于能够写入您的配置文件,那么您只需要
就不能让任何不能以管理员或权力运行的人用户运行

您的应用程序!


此外,如果您考虑将用户设置放在那里,您还只需

对于有多个用户使用机器的人来说,生活很艰难。


如果你认为多用户机器不寻常,他们就不是那个*

不寻常。它不必是多个并发用户......如果存在不同的

登录,则将应用程序配置文件中的用户设置存储起来不会很好。


您应该查看Environment.GetFolder API以了解您应该在哪里设置



-

Ian Griffiths - http://www.interact- sw.co.uk/iangblog/

DevelopMentor - http ://www.develop.com/


Hi,,
I have two questions :

1) Is it mandatory that config file of a desktop application must be
App.config

2) Is it possible to update config file in your code??

thanks for your help.
ALI

解决方案

Just create your own with strong types as you need. The following could
also me modified with encryption and/or ISO storage, etc.

MyAppConfig mac = new MyAppConfig();
mac.X = 20;
mac.Y = 40;
mac.Save();
MyAppConfig mac2 = MyAppConfig.Load();
Console.WriteLine("Name:"+mac2.Name);
Console.WriteLine("X:"+mac2.X);
Console.WriteLine("Y:"+mac2.Y);
using System;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;

namespace MyNamespace
{
/// <summary>
/// Summary description for MyAppSettings.
/// </summary>
public sealed class MyAppConfig
{
public string Name;
public int X;
public int Y;
// ... Add others...

private static readonly string file;

static MyAppConfig()
{
file = Assembly.GetExecutingAssembly().Location + ".xml";
}

public MyAppConfig()
{
Name = Assembly.GetExecutingAssembly().GetName().Name;
}

public static MyAppConfig Load()
{
using(StreamReader sr = new StreamReader(MyAppConfig.file))
{
string xml = sr.ReadToEnd();
MyAppConfig mac = MyAppConfig.FromXmlString(xml);
return mac;
}
}

public void Save()
{
string myXml = this.ToXmlString();
using(StreamWriter sw = new StreamWriter(MyAppConfig.file))
{
sw.Write(myXml);
}
}

public string ToXmlString()
{
string data = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));
using(StringWriter sw = new StringWriter())
{
ser.Serialize(sw, this);
sw.Flush();
data = sw.ToString();
return data;
}
}

public static MyAppConfig FromXmlString(string xmlString)
{
if ( xmlString == null )
throw new ArgumentNullException("xmlString");

MyAppConfig mac = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));
using (StringReader sr = new StringReader(xmlString))
{
mac = (MyAppConfig)ser.Deserialize(sr);
}
return mac;
}
}
}
--
William Stacey, MVP
http://mvp.support.microsoft.com

"ALI-R" <ne****@microsoft.com> wrote in message
news:eG**************@TK2MSFTNGP14.phx.gbl...

Hi,,
I have two questions :

1) Is it mandatory that config file of a desktop application must be
App.config

2) Is it possible to update config file in your code??

thanks for your help.
ALI




This version uses static methods and ISO storage for your assembly settings.
Potentially more usefull and don''t need to worry about file path locations
or user stepping on the file. Scope is assembly and user specific so
different user''s can have different settings. New assembly versions will
also have their own settings and not conflict with each other (i.e. user
running parallel versions.)

Usage example:
-------------------------
MyAssemConfig mac = MyAssemConfig.GetAssemConfig();
mac.X = 20;
mac.Y = 40;
MyAssemConfig.SetAppConfig(mac);

MyAssemConfig mac2 = MyAssemConfig.GetAssemConfig();
Console.WriteLine("Name:"+mac2.Name);
Console.WriteLine("X:"+mac2.X);
Console.WriteLine("Y:"+mac2.Y);

The Class:
---------------------
using System;
using System.Xml.Serialization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Reflection;

namespace MyNamespace
{
/// <summary>
/// Summary description for MyAppSettings.
/// </summary>
public sealed class MyAssemConfig
{
public string Name;
public int X;
public int Y;
// ... Add others...

//private static readonly string file;
private static readonly string isoFileName;

static MyAssemConfig()
{
//file = Assembly.GetExecutingAssembly().Location + ".xml";
isoFileName = "AssemConfig.xml";
}

public MyAssemConfig()
{
Name = Assembly.GetExecutingAssembly().GetName().Name;
}

public static MyAssemConfig Reset()
{
MyAssemConfig mac = new MyAssemConfig();
MyAssemConfig.SetAppConfig(mac);
return mac;
}

public static MyAssemConfig GetAssemConfig()
{
IsolatedStorageFile isoStore =
IsolatedStorageFile.GetStore(IsolatedStorageScope. Assembly |
IsolatedStorageScope.User, null, null);

if ( ! MyAssemConfig.ISOFileExists(isoStore, isoFileName) )
return new MyAssemConfig();

string xml = MyAssemConfig.ReadFromISOFile(isoStore, isoFileName);
try
{
MyAssemConfig mac = MyAssemConfig.FromXmlString(xml);
return mac;
}
catch
{
// Xml not valid - probably corrupted. Rewrite it with defaults.
return MyAssemConfig.Reset();
}
}

public static void SetAppConfig(MyAssemConfig appConfig)
{
if ( appConfig == null )
throw new ArgumentNullException("appConfig");
string xml = appConfig.ToXmlString();

IsolatedStorageFile isoStore =
IsolatedStorageFile.GetStore(IsolatedStorageScope. Assembly |
IsolatedStorageScope.User, null, null);
MyAssemConfig.WriteToISOFile(isoStore, isoFileName, xml);
}

// public static MyAppConfig Load()
// {
// using(StreamReader sr = new StreamReader(MyAppConfig.file))
// {
// string xml = sr.ReadToEnd();
// MyAppConfig mac = MyAppConfig.FromXmlString(xml);
// return mac;
// }
// }

// public void Save()
// {
// string myXml = this.ToXmlString();
// using(StreamWriter sw = new StreamWriter(MyAppConfig.file))
// {
// sw.Write(myXml);
// }
// }

public string ToXmlString()
{
string data = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAssemConfig));
using(StringWriter sw = new StringWriter())
{
ser.Serialize(sw, this);
sw.Flush();
data = sw.ToString();
return data;
}
}

public static MyAssemConfig FromXmlString(string xmlString)
{
if ( xmlString == null )
throw new ArgumentNullException("xmlString");

MyAssemConfig mac = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAssemConfig));
using (StringReader sr = new StringReader(xmlString))
{
mac = (MyAssemConfig)ser.Deserialize(sr);
}
return mac;
}

private static bool ISOFileExists(IsolatedStorageFile isoStore, string
fileName)
{
if ( isoStore == null )
throw new ArgumentNullException("isoStore");
if ( fileName == null || fileName.Length == 0 )
return false;

string[] names = isoStore.GetFileNames("*");
foreach(string name in names)
{
if ( string.Compare(name, fileName, true) == 0 )
return true;
}
return false;
}

private static void WriteToISOFile(IsolatedStorageFile isoStore, string
fileName, string data)
{
// Assign the writer to the store and the file TestStore.
using(StreamWriter writer = new StreamWriter(new
IsolatedStorageFileStream(fileName, FileMode.Create, isoStore)))
{
// Have the writer write "Hello Isolated Storage" to the store.
writer.Write(data);
}
}

private static string ReadFromISOFile(IsolatedStorageFile isoStore, string
fileName)
{
string sb = null;
// This code opens the TestStore.txt file and reads the string.
using(StreamReader reader = new StreamReader(new
IsolatedStorageFileStream(fileName, FileMode.Open, isoStore)))
{
sb = reader.ReadToEnd();
}
return sb.ToString();
}
}
}

--
William Stacey, MVP
http://mvp.support.microsoft.com

"William Stacey [MVP]" <st***********@mvps.org> wrote in message
news:#j**************@TK2MSFTNGP15.phx.gbl...

Just create your own with strong types as you need. The following could
also me modified with encryption and/or ISO storage, etc.

MyAppConfig mac = new MyAppConfig();
mac.X = 20;
mac.Y = 40;
mac.Save();
MyAppConfig mac2 = MyAppConfig.Load();
Console.WriteLine("Name:"+mac2.Name);
Console.WriteLine("X:"+mac2.X);
Console.WriteLine("Y:"+mac2.Y);
using System;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;

namespace MyNamespace
{
/// <summary>
/// Summary description for MyAppSettings.
/// </summary>
public sealed class MyAppConfig
{
public string Name;
public int X;
public int Y;
// ... Add others...

private static readonly string file;

static MyAppConfig()
{
file = Assembly.GetExecutingAssembly().Location + ".xml";
}

public MyAppConfig()
{
Name = Assembly.GetExecutingAssembly().GetName().Name;
}

public static MyAppConfig Load()
{
using(StreamReader sr = new StreamReader(MyAppConfig.file))
{
string xml = sr.ReadToEnd();
MyAppConfig mac = MyAppConfig.FromXmlString(xml);
return mac;
}
}

public void Save()
{
string myXml = this.ToXmlString();
using(StreamWriter sw = new StreamWriter(MyAppConfig.file))
{
sw.Write(myXml);
}
}

public string ToXmlString()
{
string data = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));
using(StringWriter sw = new StringWriter())
{
ser.Serialize(sw, this);
sw.Flush();
data = sw.ToString();
return data;
}
}

public static MyAppConfig FromXmlString(string xmlString)
{
if ( xmlString == null )
throw new ArgumentNullException("xmlString");

MyAppConfig mac = null;
XmlSerializer ser = new XmlSerializer(typeof(MyAppConfig));
using (StringReader sr = new StringReader(xmlString))
{
mac = (MyAppConfig)ser.Deserialize(sr);
}
return mac;
}
}
}
--
William Stacey, MVP
http://mvp.support.microsoft.com

"ALI-R" <ne****@microsoft.com> wrote in message
news:eG**************@TK2MSFTNGP14.phx.gbl...

Hi,,
I have two questions :

1) Is it mandatory that config file of a desktop application must be
App.config

2) Is it possible to update config file in your code??

thanks for your help.
ALI




"ALI-R" wrote:

1) Is it mandatory that config file of a desktop application must be
App.config
This is a Visual Studio-ism. This is not what the configuration file ends
up getting called, this is just what it''s called inside a Visual Studio .NET
project.

If you look in the build output directory (the bin\Release or bin\Debug
directory for C# projects, the bin directory for VB.NET projects) you''ll see
that there is a file called MyApp.exe.config, where MyApp.exe is whatever
you''ve chosen to call your application executable.

This Whatever.exe.config file is a copy of the App.Config file. VS.NET
copies it so that you don''t need to maintain a seperate debug and release
version of this file. And they use the name App.config because that''s the
magic name they''ve chosen for this behaviour. :-)
2) Is it possible to update config file in your code??



Sometimes yes, but not always, so you shouldn''t rely on being able to do
this.

Why might you not be able to? Well remember that the config file ends up in
the same directory as your executable. If it''s installed as a normal
Windows app, this will be something like c:\Program
Files\Yourcompany\Yourapp.

Normal users will not be able to write to this directory. (At least not if
it''s on an NTFS volume.) Windows protects the Program Files directory so
that only Administrators and Power Users are allowed to write into it.

So if you are relying on being able to write to your config file, you just
made it impossible for anyone not running as an admin or power user to run
your application!

Also, if you were thinking of putting user settings in there, you also just
made life difficult for anyone who has multiple users using the machine.

And if you think multi-user machines are unusual, they''re not *that*
unusual. It doesn''t have to be multiple concurrent users... If different
logins exist, storing user settings in the app config file doesn''t work
well.

You should look at the Environment.GetFolder API to see where you should be
putting settings.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/


这篇关于如何写入配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆