C#+WPF+oracle 检查文件服务器上文件是否存在

  现在有个需求,有个FTP/HTTP网站上有一堆文件,记录存在数据库。

  但根本无法知道那些文件在数据库中不存,那些文件在库里面,但不存在实体文件。

  现在做了个程序,可以做到读取数据库文件列表,然后检查网上链接是否有效,也可以反向检查。


  

<Window x:Class="WpfApplicationTest101File.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplicationTest101File"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="buttonNoFile" Content="buttonDatabaseNoExitsFile" HorizontalAlignment="Left" Margin="59,267,0,0" VerticalAlignment="Top" Width="102" Click="buttonNoFile_Click" Height="37"/>
        <Button x:Name="buttonFileNotinDatabase" Content="buttonFileNotinDatabase" HorizontalAlignment="Left" Margin="234,267,0,0" VerticalAlignment="Top" Width="102" Height="37" Click="buttonFileNotinDatabase_Click"/>
        <TextBox x:Name="textBoxWord" HorizontalAlignment="Left" Height="109" Margin="83,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="294"/>
        <TextBox x:Name="textBoxPDF" HorizontalAlignment="Left" Height="109" Margin="83,139,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="294"/>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="27,49,0,0" TextWrapping="Wrap" Text="Word" VerticalAlignment="Top"/>
        <TextBlock x:Name="textBlock_Copy" HorizontalAlignment="Left" Margin="27,172,0,0" TextWrapping="Wrap" Text="PDF" VerticalAlignment="Top"/>

    </Grid>
</Window>

using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplicationTest101File
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        List<data> allfiledata = new List<data>();
        /// <summary>
        /// 下载驱动地址
        /// Oracle Providers for ASP.NET
        ///http://www.oracle.com/technetwork/topics/dotnet/index-087367.html
        ///一般都是使用OLEDB或者是.NET中提供的OracleClient来进行连接。而微软也宣称,从.NET4.0开始放弃对OracleClient的支持,但不会删除,标记为不建议使用。 所以可以使用ORACLE提供的ADO.NET访问组件ODP.NET,组件的名字为OracleDataAccess.dll,oracle的使用和OracleClient完全一样,在程序中添加DLL引用就可以使用。
        ///
        /// 这个是.net+本机代码混合版本使用方法,此法需要安装Oracle客户端
        /// 根据Oracle客户端版本区分X86和X64位版本
        ///http://blog.csdn.net/cc_net/article/details/4740054
        ///
        /// .net驱动分OracleDataAccess .net+本机代码混合和纯.net
        /// 纯.net不需要安装Oracle客户端,但只支持.net 4以上版本
        /// 此版本不区分X86和X64位版本,一个DLL足够了
        /// 纯.net版本使用方法如下
        ///http://www.cnblogs.com/yjmyzz/archive/2013/11/01/3400999.html
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void buttonNoFile_Click(object sender, RoutedEventArgs e)
        {
            allfiledata = new List<data>();
            /// 纯.net不需要安装Oracle客户端,写法有所不同
            OracleConnectionStringBuilder builder =
               new OracleConnectionStringBuilder();
            builder.DataSource = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=PC-luozhuang)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));";

            builder.UserID = "ynstx";
            builder.Password = "ynstx2012";

            ///上面写法相当于
            string shiji = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=PC-luozhuang)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Persist Security Info=True;User ID=luozhuang;Password=luozhuang2012;";
            using (OracleConnection conn = new OracleConnection(builder.ConnectionString))
            {
                using (OracleCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select WJDM,wjmc,wjlx,cfml from FJXXB ";
                    conn.Open();
                    using (OracleDataReader reader = cmd.ExecuteReader())
                    { 
                        while (reader.Read())
                        {
                            allfiledata.Add(
                                new data()
                                {

                                    Wjdm = reader.GetString(0),
                                    Wjmc = reader.GetString(1),
                                    Wjlx = reader.GetString(2),
                                    Cfml = reader.GetString(3),
                                });
                        }
                    }
                }
            }
            StringBuilder noWord = new StringBuilder();
            StringBuilder nopdf = new StringBuilder();
            string uribase = "http://PC-luozhuang/DocService/Upload/";
            StringBuilder filename = new StringBuilder();
            for (int i = 0; i < allfiledata.Count; i++)
            {
                filename.Clear();
                filename.Append(uribase + allfiledata[i].Cfml + allfiledata[i].Wjmc + "." + allfiledata[i].Wjlx);
                if (GetWebStatusCode(filename.ToString(), 1000) != "200")
                {
                    noWord.Append(allfiledata[i].Wjdm + "," + allfiledata[i].Wjmc);
                    noWord.Append(System.Environment.NewLine);
                }
            }

            for (int i = 0; i < allfiledata.Count; i++)
            {
                filename.Clear();
                filename.Append(uribase + allfiledata[i].Cfml + allfiledata[i].Wjmc + "." + "pdf");
                if (GetWebStatusCode(filename.ToString(), 1000) != "200")
                {
                    nopdf.Append(allfiledata[i].Wjdm + "," + allfiledata[i].Wjmc);
                    nopdf.Append(System.Environment.NewLine);
                }
            }
            textBoxPDF.Text = nopdf.ToString();
            textBoxWord.Text = noWord.ToString();
        }

        public static string GetWebStatusCode(string url, int timeout)
        {
            HttpWebRequest req = null;
            try
            {
                req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "HEAD";  //这是关键        
                req.Timeout = timeout;
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                return Convert.ToInt32(res.StatusCode).ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }
        }

        private void buttonFileNotinDatabase_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder noWord = new StringBuilder();
            StringBuilder nopdf = new StringBuilder();
            string uribase = @"C:\inetpub\wwwroot\DocService\Upload";

            List<FileSystemInfo> files = EnumFile(uribase, ".doc"); //EnumFile(@"D:\doc", ".doc");
            List<FileSystemInfo> docxfiles = EnumFile(uribase, ".docx"); //EnumFile(@"D:\doc", ".docx");

            files.AddRange(docxfiles);
            OracleConnectionStringBuilder builder =
             new OracleConnectionStringBuilder();
            builder.DataSource = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=PC-luozhuang)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));";

            builder.UserID = "luozhuang";
            builder.Password = "luozhuang2012";

            ///上面写法相当于
            string shiji = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=PC-luozhuang)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Persist Security Info=True;User ID=luozhuang;Password=luozhuang2012;";
            data tdata = new data();
            using (OracleConnection conn = new OracleConnection(builder.ConnectionString))
            {
                using (OracleCommand cmd = conn.CreateCommand())
                {
                    conn.Open();
                    for (int i = 0; i < files.Count; i++)
                    {


                        cmd.CommandText = "select Wjdm,wjmc,wjlx,cfml from WJGL_FJXXB where wjmc='" + files[i].Name.Replace(files[i].Extension, "") + "' and wjlx='" + files[i].Extension.Replace(".", "") + "'";

                        using (OracleDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                tdata = new data()
                                {

                                    Wjdm = reader.GetString(0),
                                    Wjmc = reader.GetString(1),
                                    Wjlx = reader.GetString(2),
                                    Cfml = reader.GetString(3),
                                };
                            }
                            if (tdata.Wjdm == null)
                            {
                                noWord.Append(files[i].FullName);
                                noWord.Append(System.Environment.NewLine);
                                continue;
                            }
                            string filePath = uribase + tdata.Cfml.Replace("/", "\\");
                            if (files[i].FullName.StartsWith(filePath))
                            {

                            }
                            else
                            {
                                noWord.Append(files[i].FullName);
                                noWord.Append(System.Environment.NewLine);
                                continue;
                            }
                            FileInfo pdf = new FileInfo(files[i].FullName.Replace(files[i].Extension, ".pdf"));
                            if (pdf.Exists == true)
                            {
                                continue;
                            }
                            else
                            {
                                nopdf.Append(pdf.FullName);
                                nopdf.Append(System.Environment.NewLine);
                                continue;
                            }

                        }
                    }
                }

            }
            textBoxPDF.Text = nopdf.ToString();
            textBoxWord.Text = noWord.ToString();
        }

        /// <summary>
        /// 遍历指定目录下的文件
        /// </summary>
        /// <param name="path">要遍历的路径</param>
        /// <param name="currentPathOnly">是否只遍历当前目录(不处理子目录),默认为false(处理子目录)</param>
        /// <returns>所有文件列表</returns>
        public static List<FileSystemInfo> EnumFile(string path, string pattern, bool currentPathOnly = false)
        {
            List<FileSystemInfo> files = new List<FileSystemInfo>();
            // 检查目录是否存在
            if (!Directory.Exists(path))
            {
                return files;
            }

            FileSystemInfo[] fs = new DirectoryInfo(path).GetFileSystemInfos();

            foreach (FileSystemInfo fsi in fs)
            {
                // 跳过缩略图目录
                if (fsi.Name.Equals("thumb"))
                {
                    continue;
                }

                if (fsi.Attributes == (FileAttributes.Hidden | FileAttributes.System))
                { // 跳过系统和隐藏
                    continue;
                }
                if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {   // 目录
                    files.AddRange(EnumFile(fsi.FullName, pattern, false));
                    continue;
                }

                // 文件
                if (!string.IsNullOrEmpty(pattern) && !pattern.ToUpper().Equals(fsi.Extension.ToUpper()))
                { // 筛选指定的文件类型
                    continue;
                }

                files.Add(fsi);
            }

            return files;
        }
    }
}


猜你喜欢

转载自blog.csdn.net/luozhuang/article/details/51611143
今日推荐