আমি কীভাবে সি # ব্যবহার করে কোনও ফাইলের নাম পরিবর্তন করব?
আমি কীভাবে সি # ব্যবহার করে কোনও ফাইলের নাম পরিবর্তন করব?
উত্তর:
কটাক্ষপাত System.IO.File.Move , একটি নতুন নাম ফাইল "সরানো"।
System.IO.File.Move("oldfilename", "newfilename");
System.IO.File.Move(oldNameFullPath, newNameFullPath);
ফাইল.মোভ পদ্ধতিতে এটি ইতিমধ্যে বিদ্যমান থাকলে ফাইলটি ওভাররাইট করে না। এবং এটি একটি ব্যতিক্রম নিক্ষেপ করবে।
সুতরাং আমাদের ফাইলটি বিদ্যমান আছে কি নেই তা যাচাই করা উচিত।
/* Delete the file if exists, else no exception thrown. */
File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName
বা একটি ব্যতিক্রম এড়ানোর জন্য একটি চেষ্টা ক্যাচ দিয়ে এটি ঘিরে।
আপনি এটি করতে ব্যবহার করতে পারেন File.Move
।
শুধু যোগ কর:
namespace System.IO
{
public static class ExtendedMethod
{
public static void Rename(this FileInfo fileInfo, string newName)
{
fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
}
}
}
এবং তারপর...
FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
প্রথম সমাধান
System.IO.File.Move
এখানে পোস্ট করা সমাধানগুলি এড়িয়ে চলুন (চিহ্নিত উত্তর অন্তর্ভুক্ত)। এটি নেটওয়ার্কগুলিতে ব্যর্থ। তবে, অনুলিপি / মোছার প্যাটার্ন স্থানীয়ভাবে এবং নেটওয়ার্কগুলিতে কাজ করে। সরানো সমাধানগুলির মধ্যে একটি অনুসরণ করুন তবে এর পরিবর্তে অনুলিপি করুন। তারপরে মূল ফাইলটি মুছতে ফাইল.ডিলিট ব্যবহার করুন।
এটিকে সহজ করার জন্য আপনি একটি পুনর্নবীকরণ পদ্ধতি তৈরি করতে পারেন।
ব্যবহারে সহজ
সি # তে ভিবি সমাবেশটি ব্যবহার করুন। মাইক্রোসফ্ট-ভিজুয়ালবাসিকের রেফারেন্স যুক্ত করুন
তারপরে ফাইলটির নাম পরিবর্তন করতে:
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);
দুটিই স্ট্রিং। নোট করুন যে মাইফাইলের পুরো পথ রয়েছে। newName না। উদাহরণ স্বরূপ:
a = "C:\whatever\a.txt";
b = "b.txt";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
C:\whatever\
ফোল্ডারের এখন উপস্থিত থাকবে b.txt
।
smb
), ftp
, ssh
বা যাই হোক না কেন সব আছে কমান্ড / প্রিমিটিভের ফাইল সরানোর জন্য / পুনঃনামকরনের যদি না অনুমতি নেই (যেমন শুধুমাত্র পাঠযোগ্য)।
আপনি এটি একটি নতুন ফাইল হিসাবে অনুলিপি করতে পারেন এবং তারপরে System.IO.File
ক্লাসটি ব্যবহার করে পুরানোটিকে মুছুন :
if (File.Exists(oldName))
{
File.Copy(oldName, newName, true);
File.Delete(oldName);
}
দ্রষ্টব্য: এই উদাহরণ কোডে আমরা একটি ডিরেক্টরি খুলি এবং পিডিএফ ফাইলগুলি ফাইলের নামে খোলা এবং বন্ধ বন্ধনী সহ সন্ধান করি। আপনি নিজের পছন্দ মতো যে কোনও অক্ষর চেক এবং প্রতিস্থাপন করতে পারেন বা প্রতিস্থাপন ফাংশনগুলি ব্যবহার করে একটি সম্পূর্ণ নতুন নাম নির্দিষ্ট করতে পারেন।
আরও বিস্তৃত নাম পরিবর্তন করার জন্য এই কোড থেকে কাজ করার অন্যান্য উপায় রয়েছে তবে আমার মূল উদ্দেশ্যটি ছিল ফাইল কীভাবে ব্যবহার করতে হয় তা দেখাতে। আমি যখন এটি আমার ল্যাপটপে চালালাম তখন 180 টি ডিরেক্টরিতে এটি 335 পিডিএফ ফাইলের বিপরীতে কাজ করেছিল। এটি মুহুর্তের কোডটির উত্সাহ এবং এটি করার আরও বিস্তৃত উপায় রয়েছে।
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BatchRenamer
{
class Program
{
static void Main(string[] args)
{
var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");
int i = 0;
try
{
foreach (var dir in dirnames)
{
var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);
DirectoryInfo d = new DirectoryInfo(dir);
FileInfo[] finfo = d.GetFiles("*.pdf");
foreach (var f in fnames)
{
i++;
Console.WriteLine("The number of the file being renamed is: {0}", i);
if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
{
File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
}
else
{
Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
foreach (FileInfo fi in finfo)
{
Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
}
আশা রাখি,! এটা আপনার জন্য সহায়ক হবে। :)
public static class FileInfoExtensions
{
/// <summary>
/// behavior when new filename is exist.
/// </summary>
public enum FileExistBehavior
{
/// <summary>
/// None: throw IOException "The destination file already exists."
/// </summary>
None = 0,
/// <summary>
/// Replace: replace the file in the destination.
/// </summary>
Replace = 1,
/// <summary>
/// Skip: skip this file.
/// </summary>
Skip = 2,
/// <summary>
/// Rename: rename the file. (like a window behavior)
/// </summary>
Rename = 3
}
/// <summary>
/// Rename the file.
/// </summary>
/// <param name="fileInfo">the target file.</param>
/// <param name="newFileName">new filename with extension.</param>
/// <param name="fileExistBehavior">behavior when new filename is exist.</param>
public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
{
string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);
if (System.IO.File.Exists(newFilePath))
{
switch (fileExistBehavior)
{
case FileExistBehavior.None:
throw new System.IO.IOException("The destination file already exists.");
case FileExistBehavior.Replace:
System.IO.File.Delete(newFilePath);
break;
case FileExistBehavior.Rename:
int dupplicate_count = 0;
string newFileNameWithDupplicateIndex;
string newFilePathWithDupplicateIndex;
do
{
dupplicate_count++;
newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
} while (System.IO.File.Exists(newFilePathWithDupplicateIndex));
newFilePath = newFilePathWithDupplicateIndex;
break;
case FileExistBehavior.Skip:
return;
}
}
System.IO.File.Move(fileInfo.FullName, newFilePath);
}
}
এই কোডটি কীভাবে ব্যবহার করবেন?
class Program
{
static void Main(string[] args)
{
string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
string newFileName = "Foo.txt";
// full pattern
System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
fileInfo.Rename(newFileName);
// or short form
new System.IO.FileInfo(targetFile).Rename(newFileName);
}
}
ব্যবহার করুন:
using System.IO;
string oldFilePath = @"C:\OldFile.txt"; // Full path of old file
string newFilePath = @"C:\NewFile.txt"; // Full path of new file
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
File.Move(oldFilePath, newFilePath);
Using System.IO;
) সংকলন করে ?
আমার ক্ষেত্রে, আমি চাই যে নাম পরিবর্তন করা ফাইলটির নামটি অনন্য হোক, তাই আমি নামের সাথে একটি তারিখ-সময় স্ট্যাম্প যুক্ত করি। এইভাবে, 'পুরানো' লগের ফাইলের নামটি সর্বদা অনন্য:
if (File.Exists(clogfile))
{
Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
if (fileSizeInBytes > 5000000)
{
string path = Path.GetFullPath(clogfile);
string filename = Path.GetFileNameWithoutExtension(clogfile);
System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
}
}
সরান একই কাজ করছে = পুরানো একটিকে অনুলিপি করুন এবং মুছুন।
File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf",DateTime.Now));
আমার পক্ষে উপযুক্ত কোন পদ্ধতির সন্ধান পাইনি, তাই আমি আমার সংস্করণটির প্রস্তাব দিই। অবশ্যই ইনপুট দরকার, ত্রুটি পরিচালনা করা।
public void Rename(string filePath, string newFileName)
{
var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
System.IO.File.Move(filePath, newFilePath);
}
public static class ImageRename
{
public static void ApplyChanges(string fileUrl,
string temporaryImageName,
string permanentImageName)
{
var currentFileName = Path.Combine(fileUrl,
temporaryImageName);
if (!File.Exists(currentFileName))
throw new FileNotFoundException();
var extention = Path.GetExtension(temporaryImageName);
var newFileName = Path.Combine(fileUrl,
$"{permanentImageName}
{extention}");
if (File.Exists(newFileName))
File.Delete(newFileName);
File.Move(currentFileName, newFileName);
}
}
ইভেন্ট হ্যান্ডলারের ভিতরে যখন ফাইলটির নতুন নামকরণ করতে হয়েছিল, তখন আমি একটি মামলার মুখোমুখি হয়েছি, যা পুনরায় নামকরণ সহ যে কোনও ফাইল পরিবর্তনের জন্য ট্রিগার করছিল এবং চিরকালের জন্য এই ফাইলটির নাম পরিবর্তন করে এড়িয়ে যেতে হবে:
File.Copy(fileFullPath, destFileName); // both has the format of "D:\..\..\myFile.ext"
Thread.Sleep(100); // wait OS to unfocus the file
File.Delete(fileFullPath);
যদি কারও কারও সাথে এরকম দৃশ্য দেখা যায়;)
যখন সি # তে কিছু বৈশিষ্ট্য না থাকে, আমি সি ++ বা সি ব্যবহার করি:
public partial class Program
{
[DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int rename(
[MarshalAs(UnmanagedType.LPStr)]
string oldpath,
[MarshalAs(UnmanagedType.LPStr)]
string newpath);
static void FileRename()
{
while (true)
{
Console.Clear();
Console.Write("Enter a folder name: ");
string dir = Console.ReadLine().Trim('\\') + "\\";
if (string.IsNullOrWhiteSpace(dir))
break;
if (!Directory.Exists(dir))
{
Console.WriteLine("{0} does not exist", dir);
continue;
}
string[] files = Directory.GetFiles(dir, "*.mp3");
for (int i = 0; i < files.Length; i++)
{
string oldName = Path.GetFileName(files[i]);
int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
if (pos == 0)
continue;
string newName = oldName.Substring(pos);
int res = rename(files[i], dir + newName);
}
}
Console.WriteLine("\n\t\tPress any key to go to main menu\n");
Console.ReadKey(true);
}
}