【问题标题】:Convert DirectoryInfo to String in Windows Service在 Windows 服务中将 DirectoryInfo 转换为字符串
【发布时间】:2013-06-24 14:10:31
【问题描述】:

我正在尝试用 C# 编写一个项目 Windows 服务。

我想将文件夹复制到另一个目录。我写了代码,一切都很完美

DirectoryInfo source = new DirectoryInfo("C:\\belgeler");
DirectoryInfo target = new DirectoryInfo("E:\\Backup");

这是正确的实现,但是当我写这个时......

DirectoryInfo source = new DirectoryInfo(from_path);
DirectoryInfo target = new DirectoryInfo(to_path);

错误是'A field initializer cannot reference the non-static 字段、方法或属性 'BACKUP(myproject_name).Service1.veri'

//string to_path = Registry.LocalMachine.GetValue("ToPath").ToString();  
//string from_path = Registry.LocalMachine.GetValue("FromPath").ToString();

此代码块正在运行控制台应用程序,但在 Windows 服务中却不是。

【问题讨论】:

  • 是非静态字段、方法还是属性? ;)
  • "此代码块正在运行控制台应用程序,但在 Windows 服务中不是。"它作为控制台应用程序编译,但不是作为 Windows 服务?我非常怀疑...
  • from_pathto_path 是您班级的成员,还是局部变量? sourcetarget 呢?
  • 好的,我解决了。为了能够实现,它会在方法中。

标签: c# .net directoryinfo


【解决方案1】:

您的变量sourcetarget 是您的类的成员变量。允许使用以下代码:

DirectoryInfo source = new DirectoryInfo("C:\\belgeler");
DirectoryInfo target = new DirectoryInfo("E:\\Backup");

这是允许的,因为它没有引用您类的任何其他成员变量。但是当你尝试时:

DirectoryInfo source = new DirectoryInfo(from_path);
DirectoryInfo target = new DirectoryInfo(to_path);

这引用了其他变量from_pathto_path,这是不允许的。

将这些变量移动为局部变量,这应该可以解决您的问题。

【讨论】:

    【解决方案2】:

    您可以使用另一个字段作为参数来设置字段的值,您只需要在构造函数中进行。这将确保以正确的顺序设置字段。

    A field initializer cannot reference the nonstatic field, method, or property

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      相关资源
      最近更新 更多