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. 两个APP之间怎么调用《IT蓝豹》

    两个app之间怎么调用?   (1):通过显示Intent 启动    首先:配置好B app 的action,即AndroidManifest.xml中声明 <intent-filter> ...

  2. js中原型的概念

  3. 转载:Solr的自动完成实现方式(第三部分:Suggester方式续)

    转自:http://www.cnblogs.com/ibook360/archive/2011/11/30/2269126.html 在之前的两个部分(part1.part2)中,我们学会了如何配置和 ...

  4. centos7 安装jdk7

    源码包准备: 首先到官网下载jdk,http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.htm ...

  5. C# 以管理员身份运行WinForm程序

    最近帮客户开发的WinForm客户端,部分在使用的过程中,会出现“系统文件找不到”的错误提示. 调试后,确定为程序在操作配置文件时,系统权限引起的错误,直接管理员权限运行就正常了. 考虑用户操作的便利 ...

  6. Mob.com 短信验证的简单使用

    1.环境配置 http://wiki.sharesdk.cn/android-短信sdk集成文档/ a.sdk下载 http://www.mob.com/#/downloadDetail/SMS/an ...

  7. SOCKS 5协议详解(转)

    笔者在实际学习中,由于在有些软件用到了socks5(如oicq,icq等),对其原理不甚了解,相信很多朋友对其也不是很了解,于是仔细研读了一下rfc1928,觉得有必要译出来供大家参考. 1.介绍: ...

  8. 网站appache的ab命令压力测试性能

    ①:相关不错的博文链接:http://johnnyhg.iteye.com/blog/523818 ②:首先配置好对应的环境上去,有对应的命令 ③:压力测试的指令如下: 1. 最基本的关心两个选项 - ...

  9. 一个div,包含三个小的div,平均分布的样式

    从11月份开始,自学前端开发,写静态页面中,经常用到一个大的div下包含三个小的div,平均分布div大小样式,写过多次,也多次忘记,每次都要现找资料,不想之后,在这么麻烦,索性今天自己记录一下,方便 ...

  10. 关于spring boot jar包与war包的问题

    此文为转载:http://mrlee23.iteye.com/blog/2047968 在开发调试完成之后,可以将应用打成JAR包的形式,在Eclipse中可以直接使用Maven插件的package命 ...