为什么在使用计数器向名称提供文件名称时,它会给出奇怪的数字?

时间:2017-01-31 19:23:40

标签: c# .net winforms

硬盘上第一个保存的文件名是:201701311645 --- 0然后201701311645 --- 1然后201701311645 --- 20然后201701311645 --- 21然后201701311645 --- 40和201701311645 --- 41 < / p>

但我希望它保存为:201701311645 --- 0然后201701311645 --- 1然后201701311645 --- 2然后201701311645 --- 3然后201701311645 --- 4和201701311645 --- 5

在顶部我添加了一个计数器变量

private int countFilesNames = 0;

然后在dowork事件中我也将计数器重置为0,所以如果我再次启动backgroundworker,它将从0开始。

private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e)
        {
            Int32 fileNr = 0;
            countFilesNames = 0;

            if (this.SupportsProgress) { calculateFilesSize(); }

            if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); }

            while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending)
            {
                m_fileNr = fileNr;
                downloadFile(fileNr);

                if (bgwDownloader.CancellationPending)
                {
                    fireEventFromBgw(Event.DeletingFilesAfterCancel);
                    cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1);
                }
                else
                {
                    fileNr += 1;
                }
            }
        }

然后在downloadFile方法

private void downloadFile(Int32 fileNr)
        {
            FileStream writer = null;
            m_currentFileSize = 0;
            fireEventFromBgw(Event.FileDownloadAttempting);

            FileInfo file = this.Files[fileNr];
            Int64 size = 0;

            Byte[] readBytes = new Byte[this.PackageSize];
            Int32 currentPackageSize;
            System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
            Int32 readings = 0;
            Exception exc = null;

            try
            {
                writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
                    "---" + countFilesNames + ".png", System.IO.FileMode.Create);
            }
            catch(Exception err)
            {
                string ggg = err.ToString();
            }
            HttpWebRequest webReq;
            HttpWebResponse webResp = null;

            try
            {
                webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
                webResp = (HttpWebResponse)webReq.GetResponse();

                size = webResp.ContentLength;
            }
            catch (Exception ex) { exc = ex; }

            m_currentFileSize = size;
            fireEventFromBgw(Event.FileDownloadStarted);

            if (exc != null)
            {
                bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
            }
            else
            {
                m_currentFileProgress = 0;
                while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
                {
                    while (this.IsPaused) { System.Threading.Thread.Sleep(100); }

                    speedTimer.Start();

                    currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);

                    m_currentFileProgress += currentPackageSize;
                    m_totalProgress += currentPackageSize;
                    fireEventFromBgw(Event.ProgressChanged);

                    writer.Write(readBytes, 0, currentPackageSize);
                    readings += 1;

                    if (readings >= this.StopWatchCyclesAmount)
                    {
                        m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
                        speedTimer.Reset();
                        readings = 0;
                    }
                }

                speedTimer.Stop();
                writer.Close();
                webResp.Close();
                if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); }
            }
            fireEventFromBgw(Event.FileDownloadStopped);

            countFilesNames += 1;
        }

我构建了文件名:

writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
                    "---" + countFilesNames + ".png", System.IO.FileMode.Create);

将计数器向前移动1:

countFilesNames += 1;

但是我得到了其他文件名,然后我想要。

也许有更好的方法给文件名称一些身份?问题是,如果我不给文件名称一些标识,它将一直覆盖文件。文件名是相同的,内容不是,所以我需要给每个文件另一个名字。

1 个答案:

答案 0 :(得分:0)

为什么不只是在写入文件时递增计数器(因为变量看起来不像是在其他地方访问过)而不是在下面:

writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
                "---" + countFilesNames++ + ".png", System.IO.FileMode.Create);

这样,计数器不会因错误而增加。