public void Run()
{
//获取目标文件列表
string _ErrorMessage = "";
string _ErrorMessageFile = "errorLog.txt";
FileHelper fh = new FileHelper();
string servername = "";//服务器地址
string username = "";//用户名
string password = "";//用户密码
string filePath = "";//源文件目录
string targetFilePath = "";//目标目录 string _configtxt = "configtxt.txt";//配置文件
string _foldertxt = "foldertxt.txt";//源文件及目标目录列表 try
{
//获取配置文件
string configRes = GetFileString(_configtxt); if (configRes == "读取配置文件失败")
{
Console.WriteLine("读取配置文件失败");
_ErrorMessage = "读取配置文件失败";
WriteLog(_ErrorMessage, _ErrorMessageFile);
return;
}
//登录
Dictionary<string, string> dicconfig = GetDicFromStr(configRes);
try
{
servername = dicconfig["servername"];
username = dicconfig["username"];
password = dicconfig["password"];
}
catch
{
Console.WriteLine("配置文件错误");
_ErrorMessage = "配置文件错误";
WriteLog(_ErrorMessage, _ErrorMessageFile);
return;
}
//开始读取源文件数据
string folderRes = GetFileString(_foldertxt);
Dictionary<string, string> dicFolders = GetDicFromStr(folderRes);
string _defaultfolder = "";//默认拷贝目录
foreach (var folderdata in dicFolders)
{
if (folderdata.Key == "defaultfolder")
{
_defaultfolder = folderdata.Value;
continue;
}
filePath = folderdata.Key;//源文件目录 string temptargetFilePath = folderdata.Value == "" ? _defaultfolder : folderdata.Value;
//获取源文件后2个目录名
string toFilePath = filePath.Split('\\')[filePath.Split('\\').Length - ] + "\\" + filePath.Split('\\')[filePath.Split('\\').Length - ];
targetFilePath = temptargetFilePath.Trim('\\') + "\\" + toFilePath;//目标文件目录
if (!Directory.Exists(targetFilePath))
{
Directory.CreateDirectory(targetFilePath);
} //建立连接并且下载
if (FileHelper.connectState(servername, username, password))
{
string[] fileArr = fh.readlist(filePath);
//剪切所有文件
foreach (string filename in fileArr)
{
try
{
fh.FileMove(filename, targetFilePath.Trim('\\') + "\\" + GetFileNameFromPath(filename));
}
catch
{
Console.WriteLine(filename + " 文件下载失败"+DateTime.Now.ToString());
}
}
} } }
catch(Exception ex)
{
Console.WriteLine(ex.Message + ex.Source + ex.TargetSite);
_ErrorMessage = ex.Message + ex.Source + ex.TargetSite;
}
if (_ErrorMessage != "")
{
WriteLog(_ErrorMessage, _ErrorMessageFile);
} }
//写错误日志
private void WriteLog(string data,string logname)
{
try
{
FileMode fm = FileMode.Append;
if (!File.Exists(System.AppDomain.CurrentDomain.BaseDirectory+logname))
{
fm = FileMode.CreateNew;
}
string configfilename = System.AppDomain.CurrentDomain.BaseDirectory + logname;
//读取文本文件
FileStream fs = new FileStream(configfilename, fm);
StreamWriter sw = new StreamWriter(fs, Encoding.Default); sw.Write(DateTime.Now.ToString()+"---------"+ data); //释放占用
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
}
catch
{
} } private Dictionary<string, string> GetDicFromStr(string sourcestr)
{
Dictionary<string, string> dicres = new Dictionary<string, string>();
string[] datas = sourcestr.Replace("\r","").Split('\n');
foreach (string data in datas)
{
if (string.IsNullOrEmpty(data))
{
continue;
}
try
{
string[] dataarr = data.Split('=');
if (dataarr.Length == )
{ dicres.Add(dataarr[], dataarr[]);
}
else
{
dicres.Add(dataarr[], "");
}
}
catch
{ }
}
return dicres;
}
private string GetFileNameFromPath(string path)
{
return path.Split('\\')[path.Split('\\').Length - ];
}
private string GetFileString(string configname)
{
try
{
string configfilename = System.AppDomain.CurrentDomain.BaseDirectory + configname;
//读取文本文件
FileStream fs = new FileStream(configfilename, FileMode.Open);
StreamReader m_streamReader = new StreamReader(fs, Encoding.Default);
m_streamReader.BaseStream.Seek(, SeekOrigin.Begin);
//获取数据
string myFileStr = m_streamReader.ReadToEnd(); //释放占用
m_streamReader.Close();
m_streamReader.Dispose();
fs.Close();
fs.Dispose(); return myFileStr;
}
catch
{
return "读取配置文件失败";
}
}

Filehelper.cs内容

 public class FileHelper
{ System.Collections.ArrayList alst; //得到路径下所有文件(包括子文件夹下的文件)
public string[] readlist(string path)
{
alst = new System.Collections.ArrayList();//建立ArrayList对象
GetDirs(path);//得到文件夹
return (string[])alst.ToArray(typeof(string));//把ArrayList转化为string[]
} public void GetFiles(string dir)
{
try
{
string[] files = Directory.GetFiles(dir);//得到文件
foreach (string file in files)//循环文件
{
string exname = file.Substring(file.LastIndexOf(".") + );//得到后缀名
// if (".txt|.aspx".IndexOf(file.Substring(file.LastIndexOf(".") + 1)) > -1)//查找.txt .aspx结尾的文件
//if (".txt".IndexOf(file.ToLower().Substring(file.LastIndexOf(".") + 1)) > -1)//如果后缀名为.txt文件
//{
// FileInfo fi = new FileInfo(file);//建立FileInfo对象
// alst.Add(fi.FullName);//把.txt文件全名加人到FileInfo对象
//}
FileInfo fi = new FileInfo(file);//建立FileInfo对象
alst.Add(fi.FullName);
}
}
catch
{ }
} public void GetDirs(string d)//得到所有文件夹
{
GetFiles(d);//得到所有文件夹里面的文件
try
{
string[] dirs = Directory.GetDirectories(d);
foreach (string dir in dirs)
{
GetDirs(dir);//递归
}
}
catch
{
}
} //文件剪切
public void FileMove(string filePath, string toFilePath)
{
string dirPath = filePath;
string sourcePath = toFilePath;
FileInfo file = new FileInfo(dirPath);
file.MoveTo(sourcePath);
}
//建立共享文件连接
public static bool connectState(string path, string userName, string passWord)
{
bool Flag = false;
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string dosLine = @"net use " + path + " /user:" + userName + " " + passWord ;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit();
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
} }

c#下载共享文件夹下的文件并记录错误日志的更多相关文章

  1. 共享文件夹下其他文件可以访问但php文件访问不了的原因

    刚开始的问题是在virtualbox里的共享文件夹下的项目运行不了,原因是宝塔下nginx的用户和用户组默认是www 和 www 需要改成www vboxsf(因为自动挂载的目录为/media/sf_ ...

  2. vba取局域网电脑共享文件夹下的Excel文件

    Private Sub CommandButton1_Click()    Dim xlapp1 As Excel.Application    Dim xlbook1 As Excel.Workbo ...

  3. C#下载局域网共享文件夹中的文件

    在公司的局域网内部,有个主机,共享了几个文件夹给下面的客户机使用. 想要利用这个文件夹上传最新的winform程序版本,每次运行exe的时候检测局域网的软件版本达到更新exe的目的. 这里有个例子,是 ...

  4. C#遍历文件夹下所有文件

    FolderForm.cs的代码如下: using System; using System.Collections.Generic; using System.Diagnostics; using ...

  5. Delphi - 本地路径的创建、清空本地指定文件夹下的文件

    本地路径的创建 在做下载操作时,我们一般先把文件下载到本地指定的路径下,然后再做其他使用. 为了防止程序出现异常,我们通常需要先判断本地是否存在指定的路径. 以C盘Tmp文件夹为例,我们可以这样做,代 ...

  6. asp.net(C#)读取文件夹和子文件夹下所有文件,绑定到GRIDVIEW并排序 .

    Asp部分: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyFiles ...

  7. python 替换 文件夹下的 文件名称 及 文件内容

    示例效果: 1.替换某文件夹下的 文件夹及子文件夹 的名称 由OldStrDir 变为 NewStrDir: 2.替换某文件夹下的 文件夹及子文件夹 下 所有的文件的名称 由OldStrFile 变为 ...

  8. java笔试题: ——将e:/source文件夹下的文件打个zip包后拷贝到f:/文件夹下面

    将e:/source文件夹下的文件打个zip包后拷贝到f:/文件夹下面 import java.io.*; import java.util.zip.ZipEntry; import java.uti ...

  9. 【转发】du命令 实现Linux 某个文件夹下的文件按大小排序

    1. df -lh 2. du -s /usr/* | sort -rn这是按字节排序 3. du -sh /usr/* | sort -rn这是按兆(M)来排序 4.选出排在前面的10个du -s ...

随机推荐

  1. WebServers发布提示oracle客户端模式不一致

    问题:System.InvalidOperationException: 尝试加载 Oracle 客户端库时引发BadImageFormatException.如果在安装32 位Oracle 客户端组 ...

  2. 15 个有趣的 JavaScript 与 CSS 库

    原文转载:http://www.codeceo.com/article/15-interesting-js-css-framework.html 1. Wing Wing 是一个微型(压缩后仅有4KB ...

  3. redis geo 初探

    redis的geo搜索功能是3.2之后新增的,所以实验开始之前先查看redis的版本,确保版本正确. redis的geo多用于地理类应用,所以这次还是用了高德地图API来用作数据源. 首先截取几个点: ...

  4. C#批量插入数据到Sqlserver中的三种方式

    本篇,我将来讲解一下在Sqlserver中批量插入数据. 先创建一个用来测试的数据库和表,为了让插入数据更快,表中主键采用的是GUID,表中没有创建任何索引.GUID必然是比自增长要快的,因为你生 成 ...

  5. Python第二模块(文件和函数)

    1. 集合操作    集合的特点:无序,不重复的数据组合 集合的作用: 去重,将列表变为集合,就会自动去重 关系测试,测试两组数据之间的交集.差集.并集关系 常用操作: #创建集合 s = {1,2, ...

  6. oracle分组后取每组第一条数据

    数据格式: 分组取第一条的效果: sql语句: SELECT * FROM ( ;

  7. textFiled的placeHolder字体颜色

    self.title=@"修改UITextField的placeholder字体颜色"; UITextField *textTF=[[UITextField alloc]initW ...

  8. Xamarin Mono 环境搭建(使用Visual Studio 2013 开发android 和 ios )

    本文主要介绍Xamarin结合VS2013来开发Android应用程序,主要会介绍Mono和Xamarin的关系,以及整个搭建环境的过程. 一.Mono和Xamarin介绍 1.Mono简介 Mono ...

  9. IE10一下的img标签问题

    之前写过的一段简单的demo,后来在IE10以下使用的时候发现无法使用,先上一段代码 HTML: <div class="all" id="box"> ...

  10. spark 运行问题记录

    在CDH5.5.2上运行spark1.5的程序,运行起来就直接shutdown,并报出如下的异常:  INFO YarnClientSchedulerBackend: SchedulerBackend ...