I think this problem seems a lot to be questioned, but I still haven't found a solution.
I want to update my application by comparing dll. file version. I already got the file version, but when I want to update it, it gives me this error.
the code
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(#"D:\Projects\Sample\bin\Debug\Sample.dll");
FileVersionInfo myFileVersionInfo2 = FileVersionInfo.GetVersionInfo(#"C:\Projects\Sample\bin\Debug\Sample.dll");
MessageBox.Show("Version number this: " + myFileVersionInfo.FileVersion);
MessageBox.Show("Version number 2: " + myFileVersionInfo2.FileVersion);
if (myFileVersionInfo.FileVersion != myFileVersionInfo2.FileVersion)
{
string file = "Sample.dll";
string source = #"D:\Projects\Sample\MainSystem\bin\Debug\";
string target = Application.StartupPath;//#C:\
string sourceFile = System.IO.Path.Combine(source, file);
string destFile = System.IO.Path.Combine(target, file);
System.IO.File.Copy(sourceFile, destFile, true); //<< error
{
the code run when I open the application and click button
the Error
System.IO.IOException: The process cannot access the file 'C:\Projects\Sample\bin\Debug\Sample.dll' because it is being used by another process.
The Class FileVersionInfo 'locks' the dll from which you are reading the fileversion. In order to access it again, try
myFileVersionInfo2 = default(FileVersionInfo);
Related
My code processes a video file (using ffmpeg) and creates different qualities (360p, 480p, etc) and formats (mp4 and HLS) of that. After creating these files, I move all of them to another drive (a network location).
my code looks Like this:
var files = Directory.GetFiles(srcFolder);
string filename, destFile = string.Empty, srcFile = string.Empty;
try
{
for (int i = 0; i < files.Length; i++)
{
srcFile = files[i];
filename = Path.GetFileName(srcFile);
destFile = Path.Combine(destFolder, filename);
File.Move(srcFile, destFile);
}
}
catch
{
_logger.LogError("Error in moving file. srcFile: {0}, destFile: {1}", destFile, srcFile);
throw;
}
This process works fine most of the time, but for some files, I get an IO exception every time I run this process.
System.IO.IOException: The file exists. at System.IO.FileSystem.MoveFile(String sourceFullPath, String destFullPath, Boolean overwrite)
I made sure that destFolder does not exist before, nor did the destFile.
After logging the error and finding the path of source and target files, I downloaded both of them. The source file is a .ts file with a size of 1,048 KB, and the target file is an empty file with the same name (0KB).
This error happened multiple times with the same video, so I assume that it has something to do with the file itself. But I cannot figure it out.
Hello I'm beginner with C# and I want to delete the last character of my file to inject JSON objects to this file manually (I know that's not the best way to do that), so I can get the right format I tried with multiple ways like open the file, manipulating the string (deleting the last character) and when I try to replace the text in that same file I have errors like IOException: The process cannot access the file 'file path' because it is being used by another process or System.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.
I'll show you the code :
StoreLogs Log = new StoreLogs()
{
Id = ID,
DateTime = dateT,
TaskName = task,
SrcAddress = srcPath,
DstAddress = path,
FileSize = DirSize(new DirectoryInfo(srcPath)),
DelayTransfer = ts.Milliseconds,
};
// Record JSON data in the variable
string strResultJson = JsonConvert.SerializeObject(Log);
// Show the JSON Data
// Console.WriteLine(strResultJson);
// Write JSON Data in another file
string MyJSON = null;
string strPath = #"C:\Users\ASUS\Desktop\Backup\logs\log.json";
if (File.Exists(strPath))
{
//FileInfo table = new FileInfo(strPath);
//string strTable = table.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//Console.WriteLine(erase);
//StreamReader r1 = new StreamReader(strPath);
//string strTable = r1.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//r1.Close();
using (StreamReader sr = File.OpenText(strPath))
{
string table = sr.ReadToEnd();
string erase = table.Remove(table.LastIndexOf(']'));
sr.Close();
File.WriteAllText(strPath, erase);
}
//MyJSON = "," + strResultJson;
//File.AppendAllText(strPath, MyJSON + "]");
//Console.WriteLine("The file exists.");
}
else if (!File.Exists(strPath))
{
MyJSON = "[" + strResultJson + "]";
File.WriteAllText(strPath, MyJSON);
Console.WriteLine("The file doesn't exists.");
}
else
{
Console.WriteLine("Error");
}
// End
Console.WriteLine("JSON Object generated !");
Console.ReadLine();
And that's the result I want :
[{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0}]
Edit :
Thank you all for your advices
Solution:
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 1);
fs.Close();
In the code example you have posted you are opening a stream to read the file. A using block will dispose the stream after you exit the block. You are trying to write to the file, while the read stream is still accessing it (the read stream still exists). You've basically opened the file, you read from it, and are trying to write back to it while still holding it open. The reason this is a problem is that you are not using the stream to write. So your second, write, process is unable to access the file. I see you are closing the stream prior to write, but I'm willing to bet it's still holding the reference open.
I would try this method:
How to both read and write a file in C#
what it says is the access to the path (C:\Users\ASUS\Desktop\Root) denied for the user who is running the application. for ex: If you are running from Visual studio on user1 windows login then user1 should have appropriate rights to that root folder. If the code is running by itself (exe) then check the access for that user who is invoking that exe.
Based on the errors you posted seems that:
Maybe you're leaving some stream open pointing to the file you want to edit, use the 'using' statement to avoid this (see this link for more info)
You're trying to access a file when you don't have needed permissions (you aren't a system admin or file is read-only), try changing file ubication or setting it to be writeable (see this link for mor info about the UnauthorizedAccessException exception)
Hope this helps you!
I'm making a small application that have to take all the files from a shared folder and copy them in the current folder(the once from where the application it's runned).
One month ago this code was fine:
string seprin_address = #"\\PC-SEPRIN\2port\";
SimpleCopy(seprin_address);
public void SimpleCopy(string sourcePath){
try{
string fileName = "";
string targetPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
bool path = false;
string real_target = "";
for(int i = 0; i < targetPath.Length; i++){
if(targetPath[i] == 'C'){
path = true;
}
if(path){
real_target += targetPath[i];
}
}
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
/*if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}*/
// To copy a file to another location and
// overwrite the destination file if it already exists.
//System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
MessageBox.Show("Error");
}
// Keep console window open in debug mode.
}
catch(Exception e_p){
lbabel.Text = e_p.Message;
}
}
Now i get the "URI not supported error" when the file.copy it's called.
I think its supernatural but if you have any other ideas i'm all ears.
I would find out if the URI not supported is complaining about source or destination. I would also check to make sure the user that this is running as has permission to the directories in question. Could the users permissions have changed? I have had occasion where I had jobs in scheduled tasks where the user was set and later the password was changed for the user but not on the scheduled task. The same could be true if this is written as a service with a specific user.
as you are saying it was working fine one month ago, there can be two possibilities which is restricting you from accessing the Path.
1.Remote PC Hostname PC-SEPRIN might havebeen changed.Please check the remote pc hostname.
2.check the Shared Folder 2port path properly.
if somebody changes shared folder name or deletes it, you can not access it.
and also please check whether you have permissions to access it or not.
Basically I'm trying to create and export a .ics file from a C# web application so the user can save it, and open it in Outlook to add something to their calendar.
Here's the code I have at the moment...
string icsFile = createICSFile(description, startDate, endDate, summary);
//Get the paths required for writing the file to a temp destination on
//the server. In the directory where the application runs from.
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
string assPath = Path.GetDirectoryName(path).ToString();
string fileName = emplNo + "App.ics";
string fullPath = assPath.Substring(0, assPath.Length-4);
fullPath = fullPath + #"\VTData\Calendar_Event\UserICSFiles";
string writePath = fullPath + #"\" + fileName; //writepath is the path to the file itself.
//If the file already exists, delete it so a new one can be written.
if (File.Exists(writePath))
{
File.Delete(writePath);
}
//Write the file.
using (System.IO.StreamWriter file = new System.IO.StreamWriter( writePath, true))
{
file.WriteLine(icsFile);
}
The above works perfectly. It writes the file and deletes any old ones first.
My main issue is how to get it to the user?
I tried redirecting the page straight to the path of the file:
Response.Redirect(writePath);
It does not work, and throws the following error:
htmlfile: Access is denied.
NOTE: If I copy and paste the contents of writePath, and paste it into Internet Explorer, a save file dialog box opens and allows me to download the .ics file.
I also tried to prompt a save dialog box to download the file,
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "inline; filename=" + fileName + ";");
response.TransmitFile(fullPath);
response.Flush(); // Error happens here
response.End();
It does not work either.
Access to the path 'C:\VT\VT-WEB MCSC\*some of path omitted *\VTData\Calendar_Event\UserICSFiles' is denied.
Access denied error again.
What may be the problem?
It sounds like you are trying to give the user the physical path to the file instead of the virtual path. Try changing the path so it ends up in the www.yoursite.com/date.ics format instead. This will allow your users to download it. The issue is that they don't have access to the C drive on your server.
Here is a link to how to do this:
http://www.west-wind.com/weblog/posts/2007/May/21/Downloading-a-File-with-a-Save-As-Dialog-in-ASPNET
Basically, you need the following line in your code:
Response.TransmitFile( Server.MapPath("~/VTData/Calendar_Event/UserICSFiles/App.ics") );
Use this instead of the Response.Redirect(writePath); and you should be good to go.
I need to copy a file to another path, leaving the original where it is.
I also want to be able to rename the file.
Will FileInfo's CopyTo method work?
Have a look at File.Copy()
Using File.Copy you can specify the new file name as part of the destination string.
So something like
File.Copy(#"c:\test.txt", #"c:\test\foo.txt");
See also How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo, here's a sample:
FileInfo fi = new FileInfo(#"c:\yourfile.ext");
fi.CopyTo(#"d:\anotherfile.ext", true); // existing file will be overwritten
I tried to copy an xml file from one location to another. Here is my code:
public void SaveStockInfoToAnotherFile()
{
string sourcePath = #"C:\inetpub\wwwroot";
string destinationPath = #"G:\ProjectBO\ForFutureAnalysis";
string sourceFileName = "startingStock.xml";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.
You could also use File.Copy to copy and File.Move to rename it afterwords.
// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);
// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
// However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
// File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
// throw new IOException("Failed to rename file after copying, because destination file exists!");
EDIT
Commented out the "rename" code, because File.Copy can already copy and rename in one step, as astander noted correctly in the comments.
However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.
This is what I did to move a test file from the downloads to the desktop.
I hope its useful.
private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
{
string sourcePath = #"C:\Users\UsreName\Downloads";
string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] shortcuts = {
"FileCopyTest.txt"};
try
{
listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
for (int i = 0; i < shortcuts.Length; i++)
{
if (shortcuts[i]!= null)
{
File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);
listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
}
else
{
listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
}
}
}
catch (Exception ex)
{
listbox1.Items.Add("Unable to Copy file. Error : " + ex);
}
}
TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code
MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
if (Fromtb.Text=="")
{
MessageBox.Show("Ples You Should Write All Text Box");
Fromtb.Select();
return;
}
else if (Nametb.Text == "")
{
MessageBox.Show("Ples You Should Write The Third Text Box");
Nametb.Select();
return;
}
else if (Totb.Text == "")
{
MessageBox.Show("Ples You Should Write The Second Text Box");
Totb.Select();
return;
}
string fileName = Nametb.Text;
string sourcePath = #"" + Fromtb.Text;
string targetPath = #"" + Totb.Text;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
//when The User Write The New Folder It Will Create
MessageBox.Show("The File is Create in "+" "+Totb.Text);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
MessageBox.Show("The File is copy To " + Totb.Text);
}
Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code
class Program
{
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = #"E:\C-sharp-IO\test.txt";
//duplicate file path
string PathForDuplicateFile = #"E:\C-sharp-IO\testDuplicate.txt";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile);
Console.ReadKey();
}
}
Source: File I/O in C# (Read, Write, Delete, Copy file using C#)
File.Move(#"c:\filename", #"c:\filenamet\filename.txt");