Monday, 20 March 2017
On 21:22 by Vardan Kumar in C# 28 comments
File versioning, saving file with unique file name in c#
File versioning allows a user to have several versions of a file simultaneously at a particular path. Not only it intimates a user of which is the latest version i.e generated at a later stage or an older version but also provides a unique file name in the same directory.
For example....
Suppose a report generation application is developed which saves a user-readable file as an output, as discussed in earlier posts also an efficient GUI(Graphical user interface) is the most interactive one i.e. a GUI in which a user feels to have control over the application. In such an application a user is generally provided with the privilege to select his/her desired path. It is a general tendency of a computer operating individual to select same path as well as name each time he/she wants to generate the report. Now suppose user chooses a file name as cspassion.xlsx and the same file name already exists at that path, so an efficient application would save the latest version of report as cspassion(1).xlsx or cspassion(2).xlsx to avoid exception or prompting user to select if he/she wants to replace the previous version of file or not, also this would take the control from your application to the operating system which should generally be avoided as much as possible.
Logic
- First of all user selected file name or path is sent as an argument to the method fetching unique file path or creating file versions.
- Now we will check if the file already exists at that directory or not
- If not then return that file path and save the file with user selected file name at his/her desired path.
- If yes then continue with the version generation.
- Now split and store directory,file name as well as extension in different identifiers.
- Initialize number as 1,if you want to display (2) as file version after first version and initialize to 0 if you want it as (1) after first version.
- Now we'll check if a version after initial version is generated using regular expression match
- If it matches then we'll extract file name from group 1 and number from group 2.
- Now we have number as well as file name we'll loop through while the file exists in that path.
- We'll increment number by 1 in each iteration
- Format the string as filename,(number) and extension.
- Return the file path and save the workbook.
I have generated five versions of same file named cspassion for reference in current directory. Refer to image below
File Versioning C# |
Source Code
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Oracle.DataAccess.Client;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string s_oRcConnectionString = null; //Click here to know how to set dynamic connection string c#
ToolTip tt = new ToolTip();
string uniquepath=String.Empty;
private void btn_Save(object sender, EventArgs e)
{
xlWorkbook.SaveAs(uniquepath);
}
private void btn_Browse_Click_1(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();// using save file dialog
saveFileDialog1.Filter = "Excel|*.xlsx";
saveFileDialog1.Title = "Save Excel report";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
lbl_Path.Text = saveFileDialog1.FileName;
tt.SetToolTip(lbl_Path, lbl_Path.Text); // click here to read how to set tool tip for controls
lbl_Path.Visible = true;
string path=lbl_Path.Text;
uniquepath=GetUniqueFilePath(path);
}
public static string GetUniqueFilePath(string filepath)
{
if (File.Exists(filepath))
{
string fold = Path.GetDirectoryName(filepath);
string filename = Path.GetFileNameWithoutExtension(filepath);
string extension = Path.GetExtension(filepath);
int number = 1;
Match regex = Regex.Match(filepath, @"(.+) \((\d+)\)\.\w+");
if (regex.Success)
{
filename = regex.Groups[1].Value;
number = int.Parse(regex.Groups[2].Value);
}
do
{
number++;
filepath = Path.Combine(folder, string.Format("{0} ({1}){2}", filename, number, extension));
}
while (File.Exists(filepath));
}
return filepath;
}
}
}
Subscribe to:
Post Comments (Atom)
Search
Popular Posts
-
Troubleshooting Cisco VPN client Before starting troubleshooting, Let us see what VPN is and what it requires to perform its intended f...
-
Evolution-Mobile Phones With the development of portable technology,wireless communication has so evolved that (According to the announce...
-
Text Box Hint in c# Windows Form Application Text Box Hint in c# Windows Form Application While developing a windows form applicat...
-
File Versioning C# File versioning, saving file with unique file name in c# File versioning allows a user to have several versions of ...
-
Unable to set the Freeze Panes property of Window Class C# It is generally easy to resolve the compile time errors because the reason fo...
great
ReplyDeleteIEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.
DeleteIEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.
corporate training in chennai corporate training in chennai
corporate training companies in india corporate training companies in india
corporate training companies in chennai corporate training companies in chennai
I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai
This page revolves around Muzhiwan apk and Muzhiwan app download to reveal everything about Muzhiwan app store
ReplyDeleteI appreciate that you produced this wonderful article to help us get more knowledge about this topic.
ReplyDeleteI know, it is not an easy task to write such a big article in one day, I've tried that and I've failed. But, here you are, trying the big task and finishing it off and getting good comments and ratings. That is one hell of a job done!
Selenium training in bangalore
Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training
Have you ever played roulette? Well, come and play again and win a lot more than you can imagine. best roulette table Do not wait and win constantly.
ReplyDeletePretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
ReplyDeleteDigital Marketing Institute in Chennai
Digital Marketing Institute in Chennai
Best Digital Marketing Courses in Bangalore
Digital Marketing Training Institute in Coimbatore
Great blog thanks for sharing Leaders in the branding business - Adhuntt Media is now creating a buzz among marketing circles in Chennai. Global standard content creation, SEO and Web Development are the pillars of our brand building tactics. Through smart strategies and customer analysis, we can find the perfect audience following for you right now through Facebook and Instagram marketing.
ReplyDeletesocial media marketing company in chennai
Nice blog thanks for sharing Wondering where to buy healthy garden plants in Chennai for your home? Karuna Nursery Gardens offers you with tons of variety and organic choices suitable for our tropical climate. Make your garden fabulous with Karuna Nursery.
ReplyDeleteplant nursery in chennai
Excellent blog thanks for sharing Looking for the best place in Chennai to get your cosmetics at wholesale? The Pixies Beauty Shop is the premium wholesale cosmetics shop in Chennai that has all the international brands your salon deserves.
ReplyDeleteCosmetics Shop in Chennaia
Such a great information for blogger i am a professional blogger thanks…
ReplyDeleteStart your journey with Best SAP Course and get hands-on Experience with 100% Placement assistance from experts Trainers @Softgen Infotech Located in BTM Layout Bangalore. Expert Trainers with 8+ Years of experience, Free Demo Classes Conducted.
Nice post. Thanks for sharing! I want humans to understand simply how excellent this facts is to your article.
ReplyDeleteIt’s thrilling content material and Great work.
katmovies
Thanks for sharing this with us it is a worth read.
ReplyDeleteDigital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
Pretty Post! It is really interesting to read from the beginning & I would like to share your blog to my circles for getting awesome knowledge, keep your blog as updated.
ReplyDeleteSalesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Online Training | Salesforce Training
cami avizesi - cami avizeleri - avize cami - no deposit bonus forex 2021 - takipçi satın al - takipçi satın al - takipçi satın al - takipcialdim.com/tiktok-takipci-satin-al/ - instagram beğeni satın al - instagram beğeni satın al - btcturk - tiktok izlenme satın al - sms onay - youtube izlenme satın al - no deposit bonus forex 2021 - tiktok jeton hilesi - tiktok beğeni satın al - binance - takipçi satın al - uc satın al - sms onay - sms onay - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - takipcialdim.com/instagram-begeni-satin-al/ - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - perde modelleri - instagram takipçi satın al - takipçi satın al - instagram takipçi satın al - betboo
ReplyDeleteinstagram takipçi satın al
ReplyDeleteinstagram takipçi satın al
takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
aşk kitapları
tiktok takipçi satın al
instagram beğeni satın al
youtube abone satın al
twitter takipçi satın al
tiktok beğeni satın al
tiktok izlenme satın al
twitter takipçi satın al
tiktok takipçi satın al
youtube abone satın al
tiktok beğeni satın al
instagram beğeni satın al
trend topic satın al
trend topic satın al
youtube abone satın al
beğeni satın al
tiktok izlenme satın al
sms onay
youtube izlenme satın al
tiktok beğeni satın al
sms onay
sms onay
perde modelleri
instagram takipçi satın al
takipçi satın al
tiktok jeton hilesi
pubg uc satın al
sultanbet
marsbahis
betboo
betboo
betboo
beğeni satın al
ReplyDeletemarsbahis
ReplyDeletebetboo
sultanbet
marsbahis
betboo
sultanbet
ucuz takipçi
ReplyDeletebinance güvenilir mi
okex güvenilir mi
paribu güvenilir mi
bitexen güvenilir mi
coinbase güvenilir mi
instagram takipçi satın al
instagram takipçi satın alz
Aivivu chuyên vé máy bay, tham khảo
ReplyDeleteVe may bay di My
vé máy bay từ los về việt nam
khi nào có chuyến bay từ nhật về việt nam
mua vé máy bay từ đức về việt nam
từ canada về việt nam quá cảnh ở đâu
Máy bay từ Hàn Quốc về Việt Nam
giá khách sạn cách ly
vé máy bay chuyên gia nước ngoài
Thank you for this informative blog. For further information 4k ott tv box setup visit our website.
ReplyDeletegolden goose
ReplyDeletecurry 7
kevin durant shoes
golden goose sneakers
jordans
supreme clothing
yeezy supply
jordan shoes
jordan shoes
paul george shoes
smm panel
ReplyDeletesmm panel
faturalı hatta kredi
faturalı hatta kredi
instagram takipçi satın al
binance komisyon indirimi
binance indirim kodu
instagram takipçi satın al
tiktok jeton hilesi
Thanks for sharing a valuable information.
ReplyDeleteBest Interior Designers in Chennai
Best Interior Decorators in Chennai
chennai renovation
flat renovation contractor services in chennai
modular kitchen in chennai
false ceiling contractor services in chennai
carpenter services in chennai
instagram beğeni satın al
ReplyDeleteyurtdışı kargo
seo fiyatları
saç ekimi
dedektör
fantazi iç giyim
sosyal medya yönetimi
farmasi üyelik
mobil ödeme bozdurma
Smm Panel
ReplyDeleteSmm panel
iş ilanları
instagram takipçi satın al
HİRDAVATCİ
BEYAZESYATEKNİKSERVİSİ.COM.TR
servis
Tiktok jeton hilesi
Adobe Creative Cloud Crack Free Download latest. Adobe Creative Cloud 2022 Serial key offers up-to-date great creative applications. Adobe Creative Cloud .Download Creative Cloud Desktop App
ReplyDeleteDiscover the latest news, updates and system updates from the number 1 homeopathic software in the world, RadarOpus.Radar Opus Homeopathic Software Full Cracked
ReplyDeleteGood content. You write beautiful things.
ReplyDeletekorsan taksi
hacklink
mrbahis
mrbahis
vbet
vbet
taksi
sportsbet
hacklink