IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    获取项目中文件,存放到Debug中。 - 谁动了我的面包

    谁动了我的面包发表于 2015-11-05 09:56:00
    love 0

     

    说起这个,还真是费了一般功夫。

    说个最简单的方法:

    第一步:把需要生成到Debug中的文件放到项目中(注意:当前文件夹目录是什么样的,存放到Debug中也是什么样)

    第二部:设置文件属性中

      复制到输出目录(如果较新则复制:就是在内容更改后就更新,不复制:不会复制,始终复制:如果该文件需要修改,不建议选择此项)

      生成操作(无,编译,内容,嵌入的资源)

    第三步:已经完成了,是不是很简单。

     

    还有个手动的方法(哈哈,有点麻烦哦!!!):

    /// <summary>
    /// 项目中资源文件保存到Debug
    /// </summary>
    /// <param name="name">保存的文件名称。比如:"文本.txt"</param>
    /// <param name="path">项目下的路径。比如:".Demo.文本.txt"</param>
    /// <returns>0:保存失败,1:保存成功,2:文件已存在</returns>
    public int FileSaveDebug(string name, string path)
    {
    string strStartupPath = System.Windows.Forms.Application.StartupPath; //Debug路径
    string pathsave = strStartupPath + "\\" + name; //项目名称
    if (!File.Exists(pathsave))
    {
    try
    {
    string projectName = this.GetType().Assembly.GetName().Name; //项目名称
    Stream stream = this.GetType().Assembly.GetManifestResourceStream(projectName + path);
    using (FileStream fileStream = File.Create(pathsave))
    {
    const int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int len;
    do
    {
    len
    = stream.Read(buffer, 0, bufferSize);
    fileStream.Write(buffer,
    0, len);
    }
    while (len == bufferSize);
    }
    return 1;
    }
    catch (Exception ex)
    {
    return 0;
    }
    }
    else
    {
    return 2;
    }
    }

    获取项目文件内容(注意:文件属性->生成操作(必须是:嵌入的资源)):
    string content = "";  //内容
    Stream stream = this.GetType().Assembly.GetManifestResourceStream(this.GetType().Assembly.GetName().Name + ".Demo.文本.txt");
    if (stream == null)
    {
    System.Windows.Forms.MessageBox.Show(
    "读取文本失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
    }
    using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312")))
    {
    content
    = reader.ReadToEnd().ToString();
    }

     

     

     

     


    本文链接:获取项目中文件,存放到Debug中。,转载请注明。



沪ICP备19023445号-2号
友情链接